Tom
Tom

Reputation: 85

JAVA EE - EJB/CDI/JPA: Exception Handling

EJB container considers exceptions in two ways −

  • Application Exception − If business rule is violated or exception occurs while executing the business logic.

  • System Exception − Any exception, which is not caused by business logic or business code. RuntimeException, RemoteException are SystemException. For example, error during EJB lookup. RuntimeException, RemoteException are SystemException.

-> Does this means I need to use checked exceptions for my bussines logic ? Like this ?

    private void checkConstraints(Object object) throws ValidationException{
    Set<ConstraintViolation<Object>> constraintsAdress = this.getValidator().validate(object);
    if(!constraintsAdress.isEmpty()){
        String fullErrorConstraint = "";
        for (ConstraintViolation<Object> constraint : constraintsAdress) {
            fullErrorConstraint = fullErrorConstraint + constraint.getMessage() + "\n";
        }
        throw new ValidationException(fullErrorConstraint);
    }
}

@Override
public long addCafe(Cafe cafe) throws ValidationException, DBException{
    this.checkConstraints(cafe.getAddress());
    for(FootballMatch footballMatch: cafe.getNextMatchesToWatch()){
        this.checkConstraints(footballMatch);
    }
    this.checkConstraints(cafe);
    this.getManager().persist(cafe);
    return cafe.getCafeID();
}

but ...

An application exception does not automatically result in marking the transaction for rollback unless the ApplicationException annotation is applied to the exception class and is specified with the rollback element value true…

I don't fully understand it anymore ... Is it a good idea to use:

Thx in advance Cheers Tom

Upvotes: 2

Views: 616

Answers (1)

aschoerk
aschoerk

Reputation: 3593

  • ImO @ApplicationException(rollback = true) is a good idea, since then the behaviour of the container is defined. As soon as such an exception occurs, the rollback is certain.
  • You can also declare unchecked exceptions as ApplicationExceptions.

If you are interested, I compared the behavior of tomee and wildfly using some tests in: Baseclass-Bean for test

The actual testclasses are:

arquillian/wildfly and tomee/embedded

Some tests are deactivated since tomee seems not to correctly support "inherited".

Upvotes: 2

Related Questions