ExceptionMapper在Jersey 2.x&中无法正常工作. javax [英] ExceptionMapper not working consistently in Jersey 2.x & javax

查看:71
本文介绍了ExceptionMapper在Jersey 2.x&中无法正常工作. javax的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将javax and jersey用于我的api应用程序(公开api端点) 我正在尝试通过具有实现ExceptionMapper的Provider来捕获来自fastXml(在调用和发布时调用)的异常.

I am using javax and jersey for my api application (exposing api endpoints) I am trying to catch exceptions coming from fasterXml (on put and post calls) by having a Provider which implements ExceptionMapper.

我的问题是在POST或PUT上,每当我发送错误的属性名称时,有时我的映射器就会捕获异常,而有时却没有. 例如:

My Problem is that on POST or PUT, whenever I am sending wrong attributes names, sometime my mapper catch the exceptions and sometime it doesn't. For example:

  1. 运行我的应用程序一次->一切正常,捕获异常.

  1. Running my application once -> everything is working as expected, catching exceptions.

再次运行我的应用程序(重新启动)->映射器什么也没捕获

Running my application again (restart) -> the mapper does not catch nothing

我使用的是Jersey 2.x,托管在tomcat中(不使用spring或类似的工具).

I am using Jersey 2.x, hosting in tomcat (not using spring or anything like that).

web.xml:

<servlet>
    <servlet-name>api-service-endpoints</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>
            com.api.providers,
            com.api.resources
        </param-value>

    </init-param>
    <init-param>
        <param-name>jersey.config.server.provider.classnames</param-name>
        <param-value>org.glassfish.jersey.filter.LoggingFilter</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

提供者代码:

@Provider
public class JsonMappingExceptionProvider
    implements ExceptionMapper<JsonMappingException> {

public JsonMappingExceptionProvider() {
    log.info("JsonMappingExceptionProvider created..");
}

private static final Logger log = LoggerFactory
        .getLogger(JsonMappingExceptionProvider.class);

@Override
public Response toResponse(JsonMappingException exception) {
    log.error("Error while parsing input", exception);
    Response response = createBadRequestResponse();
    return response;
}

有什么想法吗?

推荐答案

我在

I found the solution with the help of Jersey Exception mappers not working when jackson deserialization fails

由于jersey试图在其映射器列表中查找给定异常的最佳匹配,因此您必须将映射器映射到您要捕获的确切异常,因为映射器的顺序是任意的.杰克逊拥有自己的通用json异常映射器,因此,您应该尝试使映射器捕获所需的异常.

Since jersey is trying to find the best match for the given exceptions within it's list of mappers, you have to map your mapper to the exact exception you are trying to catch, since the order of the mapper is arbitrary. Jackson has it's own mapper for general json exception, therefore you should try to make your mapper catch the exceptions you want.

这篇关于ExceptionMapper在Jersey 2.x&amp;中无法正常工作. javax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆