Da49
Da49

Reputation: 117

Application Exception in one class being returned to the calling class as an EJBTransactionRollbackException

I am having some trouble regarding an exception being thrown when I don't want it to be. Here are my two classes:

public List<ErrorResponse> validate()
{
    List<ErrorResponse> errors = new ArrayList<ErrorResponse>();

    try
    {
        Users user = userManager.findByCompany(job.getCompanyId().getId());
    }
    catch (Exception e)
    {
        ErrorCodes err = ErrorCodes.CODE101;
        errors.add(new ErrorResponse(err.getCode(), err.getMessage()));
    }
}


public Users findByCompany(Integer companyId) 
        throws UserNotFoundException, UsernameNotProvidedException
{
    if (username == null)
    {
        throw new UserUsernameNotProvidedException();
    }

    TypedQuery<Users> query = em.createNamedQuery("Users.findByCompany", Users.class);
    query.setParameter("companyId", companyId);
    try
    {
        Users result = query.getSingleResult();
        return result;
    }
    catch (NoResultException e)
    {
        throw new UserNotFoundException();
    }
    catch (NonUniqueResultException e)
    {
        throw new UserNotFoundException();
    }
    catch (Exception e)
    {
        throw new UserNotFoundException();
    }
}

Ok - so the validate() method calls the findByCompany() method (in another class). The exception being thrown is the runtime 'NonResultException' (which is correct) in the findByCompany() method. This is then CAUGHT in the same method, and my application Exception 'UserNotFoundException' is thrown. This should now propagate to the validate() method, where it should be caught in the 'catch(Exception e)'. However instead, the 'catch(Exception e)' in validate() is catching an 'EJBTransactionRolledBackException' instead, which is not what I want - The application should continue if no results are found.

Surely by catching the runtime exception and throwing my application exception (and again, catching that in the validate() method), the rollback should be avoided?

Thanks in advance.

Upvotes: 1

Views: 144

Answers (1)

kostja
kostja

Reputation: 61558

Exceptions that extend RuntimeException or RemoteException and are not annotated with @ApplicationException are considered system exceptions and are therefore wrapped in an EJBException.

You may either want to throw a checked Exception (probably not) or annotate your exception class.

This can also be configured inside a deployment descriptor XML, but I am not aware of the details.

Upvotes: 2

Related Questions