简体   繁体   中英

How to handle unexpected exceptions in JAX-RS

My technology stack is Tomcat (servlet 3.0), Jersey for JAX-RS, Spring and Hibernate. When something unexpect goes wrong like some data conversion error in Hibernate, I do not want the clients to see my stacktrace for those exceptions that the Tomcat tries to print by default. However I would like to log those exceptions so I can find what is wrong and fix things.

My first try was using ExceptionMapper from JAX-RS and naively thinking that would solve my problems. But then I noticed that Jersey throws it's own exceptions for example urls that are not mapped are com.sun.jersey.api.NotFoundExceptions. This causes 404 exceptions to be logged which I don't want. Worse, the client no longer gets 404 but a status code 500.

I could just create exception mappers for the exceptions that jersey throws but I could miss something. Is there a best practice for something like this?

Jersey直接抛出的所有异常都是WebApplicationException的子类,因此,如果要捕获所有异常,只需为该类创建ExceptionMapper就可以了。

Take a look at this page: http://www.rexsl.com/rexsl-core/trap.html . It explains how you can/should catch all runtime exceptions in a web application. Suggested solution with ExceptionMapper will only catch JAX-RS exceptions, which is not enough, especially if you're using DB and Hibernate.

Source code of the ExceptionTrap class is here .

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