使用 Jersey ExceptionMapper 将异常映射到响应时回滚事务

rollback transaction when mapping exception to responses with Jersey ExceptionMapper

我正在使用自定义 Jersey ExceptionMapper 将未经检查的异常映射到错误响应中(如 documentation 中所述)。我的问题是事务没有回滚,在异常之前所做的每个数据库修改都被保留。

如果我不使用 ExceptionMapper,而是抛出 WebApplicationException,也会发生同样的事情。

如何向客户端发送错误响应以保持正常行为(回滚事务)? 我发现了一个类似的问题here,但我没有使用spring。

您可以使用 RequestEventListener to manage the transaction throughout the lifetime of the request. You can listen for RequestEvent.Types,其中包括 RESOURCE_METHOD_STARTON_EXCEPTIONRESOURCE_METHOD_FINISH 等事件。您可以在请求处理的开始并提交或回滚事务,具体取决于它是成功处理还是抛出异常。

这几乎就是 Dropwizard does with it's @UnitOfWork. You can see how it is all implemented in this package. Look at the UnitOfWorkApplicationEventListener。您将看到他们如何实现我上面所说的内容。