如何从 REST 端点捕获 JsonParseException [英] How to catch JsonParseException from REST endpoint

查看:49
本文介绍了如何从 REST 端点捕获 JsonParseException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的端点:

@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...

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

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

推荐答案

实现一个ExceptionMapper核心/JsonParseException.html" rel="noreferrer">JsonParseException.它将允许您将给定的异常映射到响应.请看下面的例子:

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

然后在您的 ResourceConfig 子类(见注释):

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

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

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

<小时>

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


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

注意2:优先考虑自己的ExceptionMapper 如果你有 JacksonFeature 已注册并且您希望覆盖 JsonParseExceptionMapperJsonMappingExceptionMapper 附带 jackson-jaxrs-json-provider 模块.有关详细信息,请参阅此答案.

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.

这篇关于如何从 REST 端点捕获 JsonParseException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆