【问题标题】:Can't catch 400 Bad Request with javax.ws.rs.ext.ExceptionMapper无法使用 javax.ws.rs.ext.ExceptionMapper 捕获 400 错误请求
【发布时间】:2020-02-12 05:42:19
【问题描述】:

我有一个使用POST http 方法并接受application/json 的REST 服务方法。 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" },则不会记录任何错误,但网络服务器会返回:

HTTP/1.1 400 Bad Request
Server: WildFly/11

Unrecognized field "aaa" (class HierResult), not marked as ignorable

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

我为java.lang.Exception注册了一个ExceptionMapper,但是它只能捕获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);
    }        
}

【问题讨论】:

  • 没有抛出 BadRequestException,所以没有什么可捕获的。发生的情况是,Jackson 为 JsonParseException 和 JsonMappingException 提供了 ExceptionMappers,它们返回 400 的响应。您必须为相同的异常创建自己的映射器才能覆盖此行为。
  • 我需要完全一样的。有没有人分享一些代码来解决这个问题?
  • @phe 看到答案

标签: java jax-rs wildfly wildfly-11


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2021-01-20
    • 1970-01-01
    • 2021-07-27
    • 1970-01-01
    • 2017-11-27
    • 2013-06-30
    • 1970-01-01
    • 2019-12-03
    • 1970-01-01
    相关资源
    最近更新 更多