首页 > 解决方案 > 无法使用 javax.ws.rs.ext.ExceptionMapper 捕获 400 错误请求

问题描述

我有一个 REST 服务方法,它使用POSThttp 方法并接受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

所以问题是:我如何记录这个错误?

我注册了一个ExceptionMapperfor 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);
    }        
}

标签: javajax-rswildflywildfly-11

解决方案


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

推荐阅读