3

I have an endpoint like this:

@POST
public Response update(MyDocument myDocument){}

If the request is not valid, my server would get some quite long logs like this:

javax.servlet.ServletException: org.glassfish.jersey.server.ContainerException: com.fasterxml.jackson.core.JsonParseException: Unexpected character....
...
Caused by...
...
Caused by...

The exception is hard to be avoided completely, so I am wondering how could I catch the JsonParseException?

Spider
  • 1,380
  • 4
  • 22
  • 42

1 Answers1

7

Implement an ExceptionMapper for JsonParseException. It will allow you to map the given exception to a response. See the example below:

@Provider
public class JsonParseExceptionMapper implements ExceptionMapper<JsonParseException> {

    @Override
    public Response toResponse(JsonParseException exception) {
        return Response.status(Response.Status.BAD_REQUEST)
                       .entity("Cannot parse JSON")
                       .type(MediaType.TEXT_PLAIN)
                       .build();
    }
}

And then register it with a binding priority in your ResourceConfig subclass (see notes):

@ApplicationPath("api")
public class JerseyConfig extends ResourceConfig {

    public JerseyConfig() {
        register(JsonParseExceptionMapper.class, 1);
    }
}

If you are not using a ResourceConfig subclass, you can annotate the ExceptionMapper with @Priority (see notes):

@Provider
@Priority(1)
public class JsonParseExceptionMapper implements ExceptionMapper<JsonParseException> {
    ...
}

Note 1: You may also find it helpful to create another ExceptionMapper for JsonMappingException.

Note 2: Giving a priority to your own ExceptionMappers is particularly useful if you have the JacksonFeature registered and you want to override the behavior of JsonParseExceptionMapper and JsonMappingExceptionMapper that come with the jackson-jaxrs-json-provider module. See this answer for further details.

cassiomolin
  • 124,154
  • 35
  • 280
  • 359