How to customize JAX-RS application exception handling?

Hello,

I have configured a simple JAX-RS (not WebEngine as it is for programmatic web services) application as described in the documentation. I am using the

Nuxeo-WebModule: org.nuxeo.ecm.webengine.jaxrs.scan.DynamicApplicationFactory

line to discover my JAX-RS classes.

Everything is working as I need, with the small detail that the text/plain error response for WebExceptions that are raised in my JAX-RS classes includes the stack trace. I want them to only include the status line with an empty body.

What is the correct way to avoid/modify this behavior? I tried putting an ExceptionMapper implementation in my JAX-RS package but the DynamicApplicationFactory does not seem to discover/apply it. It is annotated with @Provider and is in the correct package.

Thanks.

0 votes

1 answers

2063 views

ANSWER



You can override the handleError() method in your ModuleRoot class. Here is a sample

@Override
public Object handleError(WebApplicationException e) {
    if (e instanceof WebSecurityException) {
        return Response.status(401).entity(
                getTemplate("error/error_401.ftl")).type("text/html").build();
    } else if (e instanceof WebResourceNotFoundException) {
        return Response.status(404).entity(
                getTemplate("error/error_404.ftl")).type("text/html").build();
    } else {
        return super.handleError(e);
    }
}
0 votes



Hmm, I don't have a ModuleRoot class. I just have POJOs annotated with the JAX-RS @Path and @Provider, and the DynamicApplicationFactory is doing the correct thing with respect to making those available.

I basically stopped reading before the line "Declaring a WebEngine Application in Nuxeo" since I was only interested in a JAX-RS application.

Will I need to subclass ModuleRoot to customize this behavior?

03/20/2014

Ok, sorry i didn't read well your message and thought you were in a WebEngine app. BTW you can use WebEngine for a "programatic webservice" : we use it for instance in the Rest API and it provides some helpers to deal with documents. I will look for the proper way to do it in JAX-RS and come back to you.
03/21/2014

Thanks for your help! I did look at the rest of the documentation and decided against using the WebEngine app for the time being, mostly because I really didn't need any of the .ftl or other tools for building more complex systems, since this is only a couple of JSON-driven web services for creating and polling specific documents in the repository.

I currently have a workaround which involves using a ContainerResponseFilter to remove the body from error responses, but clearly this is worse than stopping the stack trace from being printed in the first place.

03/21/2014

Any more thoughts on this, Damien? I'm prepared to accept "there isn't a way right now" as an answer for now. :)
03/31/2014