2
votes

I'm using a custom Jersey ExceptionMapper to map my unchecked exceptions into error responses (as described in the documentation). My problem is that the transaction is not rolled back, every DB modification made before the exception is persisted.

The same thing happens if, instead of using the ExceptionMapper, I throw a WebApplicationException.

How can I send an error response to the client preserving the normal behavior (rollback the transaction)? I found a similar question here, but I don't use spring.

1

1 Answers

1
votes

What you can do is use a RequestEventListener to manage the transaction throughout the lifetime of the request. You can listen for RequestEvent.Types, which includes events such as RESOURCE_METHOD_START, ON_EXCEPTION, RESOURCE_METHOD_FINISH, etc. You can begin the transaction at the beginning of the request processing and commit or rollback the transaction depending on if it a successful processing or an exception is thrown.

This is pretty much what Dropwizard does with it's @UnitOfWork. You can see how it is all implemented in this package. Look at the UnitOfWorkApplicationEventListener. You'll see how they implement what I was talking about above.