I need some direction how to best use Exceptions in a Java EE environment, serving clients via JAX-RS.
At the moment, I have a number of exceptions, all extending RuntimeException, and annotated with @ApplicationException(rollback=false). In order to transport them to the clients, they carry a JAXB-annotated entity; and an ExceptionMapper is ready to convert them to proper, meaningful HTTP Responses (HTTP Status codes included).
I have nothing specified regarding transactional behaviour, so I guess it defaults to CMT.
Great stuff so far: when the server decides, it cannot fulfill a request, because input data is not valid/sufficient/whatever, it throws one of my BadRequestException, which makes it to the JAX-RS resource, where it gets mapped to a HTTP Response. Client is informed about what went wrong.
The issue I have is that I always get a javax.ejb.TransactionRolledbackLocalException, caused by BadRequestException! I don’t want the transaction to be rolled back! The @ApplicationException seems to be ignored…
Should I not extend from RuntimeException but rather use checked exceptions? I though @ApplicationException was supposed to be the right way…
For background information: all of my Exceptions leave the container/beans in a working state. No need for the bean instance to be destroyed or stuff like that.
Ok, turns out reading the manuals does help sometimes :).
An
@ApplicationExceptionis by definition not aRuntimeException. In fact, throwingRuntimeExceptionsseems to be a very bad idea, that’s what’ll tear down a bean instance, rollback transactions, etc.After switching everything to be based on checked Exceptions, my code not only looks much better, the IDE supports me much better as well. And it works like a charm. Now I can control, if my
ApplicationExceptionshould cause transaction rollback or not.I found this link useful, even though it describes it for Bea Weblogic.