How to catch JsonParseException from REST endpoint

限于喜欢 提交于 2019-12-20 03:22:10

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/50333676/how-to-catch-jsonparseexception-from-rest-endpoint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!