How to suppress Jersey exceptions that Jersey throws automatically?

2.1k Views Asked by At

I am using Jersey 1.14 for REST in JAVA. If there is any error in POST body of a resource, Jersey throws and exception which mentions my internal classes to client. I continue wanting to give them error when the error is passed from my application, but suppress errors that are being thrown by Jersey(for the requests which does not even get to my application, as Jersey identifies the exception and throw it). I searched for any flag to achieve this, but could not find anything. Is there a way to do this?

EDIT: Rephrasing the question: mute/suppress error stack trace for invalid input in jersey

UPDATE: I tried using ExceptionMapper, catching java.lang.Exception. It catches excpetion like when there is Content-Type missing, but fails to catch exception when there is an error in object conversion.

4

There are 4 best solutions below

1
On

Jersey will throw exceptions which are not handled in your code. So you need to wrap your webservice code in try/catch. And catch the Exception class in to make sure that you handle it gracefully in your web service class.

0
On

If you are parsing xml you can write a custom ContextResolver to catch the exception. I case of json you may need a messagebodyreader/writer

3
On

I believe this can be achieved through server configuration, since Jersey does not seem to have any relevant configuration option.

Which servlet container are you using?


(EDIT) For Tomcat search for "tomcat suppress exception stack trace". Most answers will have you place an error-page element in your web.xml:

<error-page>
    <exception-type>java.lang.Throwable</exception-type>
    <location>/your-custom-error-page.jsp</location>
</error-page>

And, of course, implement a your-custom-error-page.jsp that does not include the stack trace. It may also check application environment and present the stack trace only in DEVELOPMENT.

2
On

You can use ExceptionMapper. Here's an old article about it that will do.