我有一个 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);
}
}