问题
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?
回答1:
All exceptions thrown directly by Jersey are subclasses of WebApplicationException, so if you want to catch them all just create an ExceptionMapper for that class and you'll be good.
回答2:
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.
来源:https://stackoverflow.com/questions/14562473/how-to-handle-unexpected-exceptions-in-jax-rs