Search code examples
javajpajta

How to rollback a transaction with a catched exception?


I have a Rest API and I want catch all exceptions to send a custom message for client when some error is thrown.

I catched the exceptions with try { ... } catch (Exception e) { ... } but, in these mode, the rollback doesn't execute and the data are persisted.

@POST
@Transactional
public Response add(Foo foo) {
    try {
        Foo add = this.service.add(foo);

        return Response.status(CREATED)
                .entity(add)
                .build();
    } catch (Exception e) {
        return Response.status(BAD_REQUEST)
                .entity("Contact the support! Error: " + e.getMessage())
                .build();
    }
}

I want rollback the transaction because the data are incorrect.


Solution

  • When you're using @Transactional it's already taken care of. You don't have to do rollback on your own (it's a bit like try-with-resources). You would have to rollback transaction, when using explicitly Transaction in finally clause of try.