Jersey unable to catch any Jackson Exception

感情迁移 提交于 2019-12-04 03:27:16

Had the same problem.
The problem is that JsonMappingExceptionMapper kicks in before your mapper.

The actual exception is of class com.fasterxml.jackson.databind.exc.InvalidFormatException and the mapper defines com.fasterxml.jackson.jaxrs.base.JsonMappingException, so it's more specific to the exception.
You see, Jersey's exception handler looks to find the most accurate handler (see org.glassfish.jersey.internal.ExceptionMapperFactory#find(java.lang.Class, T)).

To override this behavior, simply disable the mapper from being used:

  1. Using XML: <init-param> <param-name>jersey.config.server.disableAutoDiscovery</param-name> <param-value>true</param-value> </init-param>

  2. Using code: resourceConfig.property(CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true); where resourceConfig is of type org.glassfish.jersey.server.ServerConfig.


You can also write your own specific mapper:

public class MyJsonMappingExceptionMapper implements ExceptionMapper<JsonMappingException>

But I think it's an over kill.

Hi it seems to exits an alternative answer now that does not require to disable Jersey AUTO_DISCOVERY feature.

Just annotate your own exception mapper with a @Priority(1) annotation. The lower the number, the higher the priority. Since Jackson's own mappers do not have any priority annotation, yours will be executed:

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