java - 无法使用 javax.ws.rs.ext.ExceptionMapper 捕获 400 错误请求
问题描述
我有一个 REST 服务方法,它使用POST
http 方法并接受application/json
. JSON 绑定到一个 JAXB bean:
@POST
public void test(final HierResult obj) throws Exception {
printHierResult(obj);
}
@XmlRootElement
public static class HierResult {
public String dummy;
}
我注意到,当有人向我发送包含未知字段的语法有效 JSON 时,说{ "aaa": "bbb" }
没有记录错误,但 Web 服务器返回:
HTTP/1.1 400 Bad Request
Server: WildFly/11
Unrecognized field "aaa" (class HierResult), not marked as ignorable
所以问题是:我如何记录这个错误?
我注册了一个ExceptionMapper
for java.lang.Exception
,但它只能捕获JsonParseException
或我的 java 方法抛出的异常,而不是上面的错误。
@Provider
public class MyExceptionLogger implements ExceptionMapper<Exception> {
private static final Logger LOGGER = LoggerFactory.getLogger(MyExceptionLogger.class);
@Override
public Response toResponse(final Exception exception1) {
LOGGER.error("", exception1);
return Response
.serverError()
.status(Response.Status.BAD_REQUEST)
.entity(String.valueOf(exception1.toString()))
.build();
}
}
@javax.ws.rs.ApplicationPath("webresources")
public class ApplicationConfig extends Application {
@Override
public Set<Class<?>> getClasses() {
final Set<Class<?>> resources = new java.util.HashSet<>();
addRestResourceClasses(resources);
return resources;
}
private void addRestResourceClasses(final Set<Class<?>> resources) {
resources.add(MyExceptionLogger.class);
}
}
解决方案
正如@PaulSamsotha 评论的那样,必须注册一个具有相同或更多价格异常类的映射器。
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<version>2.10.2</version>
<artifactId>jackson-databind</artifactId>
<scope>provided</scope>
</dependency>
_
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
public class TestMapper implements ExceptionMapper<UnrecognizedPropertyException> {
private static final Logger LOGGER = LoggerFactory.getLogger(TestMapper.class);
@Override
public Response toResponse(final UnrecognizedPropertyException exception1) {
LOGGER.error("server side error", exception1);
return Response
.serverError()
.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(String.valueOf(Response.Status.INTERNAL_SERVER_ERROR))
.build();
}
}
推荐阅读
- ios - 使用 CoreData 和数组填充表视图部分
- java - zeroDateTimeBehavior=convertToNull 在使用休眠的 jdbc url 中不起作用
- html - woocommerce 电子邮件中的 TM 符号图像而不是 unicode 特殊字符
- excel - 比较产生意外结果的字符串
- awk - 使用 AWK 时无输出
- git - 签出远程分支而不跟踪它
- c# - 访问 KeyValuePair 的键只返回字符串“Key”
- java - IMEI验证java将字符串转换为长丢失前导0
- jquery - removeClass() 方法无法删除应用于 div 的 css
- javascript - 如何将图像文件从输入存储到js中的变量中?