ExceptionMapper not working consistently in Jersey 2.x & javax

妖精的绣舞 提交于 2021-02-20 03:49:38

问题


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.

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. Running my application once -> everything is working as expected, catching exceptions.

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

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 Code:

@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;
}

Any ideas?


回答1:


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

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.



来源:https://stackoverflow.com/questions/39910075/exceptionmapper-not-working-consistently-in-jersey-2-x-javax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!