Jersey Could Not Catch Jackson's Exception

For my REST api, I use jersey and ExceptionMapper to detect global exceptions. It works fine in all exceptions thrown by my application, but I cannot catch the exception thrown by jackson.

For example, one of my endpoints takes an object containing an enumeration. If Json in the request has a value that is not in the enumeration, introduce this exception

Can not construct instance of my.package.MyEnum from String value 'HELLO': value not one of declared Enum instance names: [TEST, TEST2] at [Source: org.glassfish.jersey.me ssage.internal.ReaderInterceptorExecutor$UnCloseableInputStream@ 5922e236; line: 3, column: 1] (through reference chain: java.util.HashSet[0]->....) 

Even if I created this mapper

 @Provider @Component public class JacksonExceptionMapper implements ExceptionMapper<JsonMappingException> { @Override public Response toResponse(JsonMappingException e) { .... } } 

Code never reaches this converter.

Is there something we need to do to catch these exceptions?

EDIT Note. My Jus tried to be less general, and instead of JsonMappingException I use InvalidFormatException, in this case mapper is called. But I still don't get it, because InvalidFormatException extends JsonMappingException and should also be thrown

+6
source share
1 answer

There was the same problem.
The problem is that JsonMappingExceptionMapper is triggered in front of your mapper.

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

To override this behavior, simply disable the use of the converter:

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

  • Code usage: 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 cartographer:

 public class MyJsonMappingExceptionMapper implements ExceptionMapper<JsonMappingException> 

But I think it kills.

+3
source

All Articles