如何从 REST 端点捕获 JsonParseException

How to catch JsonParseException from REST endpoint

我有一个这样的端点:

@POST
public Response update(MyDocument myDocument){}

如果请求无效,我的服务器会得到一些很长的日志,如下所示:

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

这个异常是很难完全避免的,所以我想知道如何捕获JsonParseException?

实施 ExceptionMapper for JsonParseException。它将允许您将给定的异常映射到响应。请参阅以下示例:

@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();
    }
}

然后在你的ResourceConfig子类中用绑定优先级注册它(见注释):

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

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

如果您没有使用 ResourceConfig 子类,您可以将 ExceptionMapper 注释为 @Priority (见注释):

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

注 1: 您可能还会发现创建另一个 ExceptionMapper for JsonMappingException.

很有帮助

注2:优先考虑自己的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 了解更多详情。