Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jersey unable to catch any Jackson Exception

For my REST api I'm using jersey and ExceptionMapper to catch global exceptions. It works well all the exception my app throws but I'm unable to catch exception thrown by jackson.

For example one of my endpoint accept an object that contains an enum. If the Json in the request has a value that is not in the enum jersey throw this exception back

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.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream@5922e236; line: 3, column: 1] (through reference chain: java.util.HashSet[0]->....)

Even though I have created this mapper

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

The code never reach this mapper.

Is there anything we need to do in order to catch these exceptions?

EDIT Note: I have jus tried being less general and instead of JsonMappingException I use InvalidFormatException in this case the mapper is called. But I still don't understand because InvalidFormatException extends JsonMappingException and should be called as well

like image 723
Johny19 Avatar asked Jan 05 '16 15:01

Johny19


Video Answer


2 Answers

Starting in version 2.29.1 [1], if you're registering the JacksonFeature, you can now do so without registering the exception mappers [2]:

register(JacksonFeature.withoutExceptionMappers());

[1] https://github.com/eclipse-ee4j/jersey/pull/4225

[2] https://eclipse-ee4j.github.io/jersey.github.io/apidocs/2.34/jersey/org/glassfish/jersey/jackson/JacksonFeature.html#withoutExceptionMappers--

like image 71
shelley Avatar answered Oct 12 '22 12:10

shelley


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>
like image 34
matteosilv Avatar answered Oct 12 '22 13:10

matteosilv