Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java EE: @ApplicationException thrown, still rolls back transactions

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.

like image 200
Hank Avatar asked Aug 14 '26 07:08

Hank


2 Answers

For others struggling with same problem: Annotation @ApplicationException is ignored(Not scanned/not processed) when Exception class is not included in ejb-jar. That is a common case when our ApplicationException is a part of API jar. In that case we have to use XML descriptor to mark ApplicationException.

Looking here helped me -> https://www.java.net//node/665096

like image 144
woczkowski Avatar answered Aug 16 '26 05:08

woczkowski


Ok, turns out reading the manuals does help sometimes :).

An @ApplicationException is by definition not a RuntimeException. In fact, throwing RuntimeExceptions seems 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 ApplicationException should cause transaction rollback or not.

I found this link useful, even though it describes it for Bea Weblogic.

like image 21
Hank Avatar answered Aug 16 '26 06:08

Hank



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!