简体   繁体   中英

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM