本文介绍了如何从 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();
}
}
然后在您的 子类:
And then register it with a binding priority in your ResourceConfig
subclass :
@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> {
...
}
这篇关于如何从 REST 端点捕获 JsonParseException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!