Question

I develope a registration function. A new user account will be created in the database, and after that a welcome email will be sent. The email sending function can execute a exeption. If a exception will be thrown the created user account has to be deleted. The problems is that my stateless bean rollbacks only if an unchecked exception will be thrown. My exception is a checked exception. Either I have to wrap in a unchecked exception, then I cant response with a proper http status code (using jax rs) or I have to execute a manual rollback.

Can someone help and offer a better solution for my scenario?

Thanks!

Was it helpful?

Solution

You can annotate your checked exception with the annotation: @ApplicationException(rollback = true).

e.g.:

@ApplicationException(rollback = true)
public class MyApplicationException extends Exception{
}

This will mark the current transaction for rollback.

Edit:

I do not want to use a exception to execute a rollback because I cant response with a http status code

Other alternative is to explicitly marks the transaction for rollback using the SessionContext.setRollbackOnly() method. I don't know your app design, but an example would be:

@Stateless
public class MyBean(){

    @Resource
    private SessionContext ctx;

    public void doSomething() {
        try {
            //code that sends a mail
        } catch (Exception e) {
            ctx.setRollbackOnly(); //the transaction will not commit
           //log exception

        }
    }
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top