Reputation: 1597
We are implementing a RestSerivce and we have an issue that Jersey handles JsonMappingException
What we would like to do is wrapping all exceptions to a specific class RestError. But the problem is that the Jersey JsonMappingException won't be catched in the ExceptionMapper
The RestError class
@XmlRootElement(name = "error")
@XmlAccessorType(XmlAccessType.FIELD)
public class RestError {
private int statusCode;
private RestErrorCode errorCode;
private String message;
private List<String> fullStackTrace;
}
The ExeceptionMapper class
@Provider
@Priority(Priorities.USER)
public class ThroawableExceptionMapper implements ExceptionMapper<Throwable> {
@Override
public Response toResponse(Throwable throwable) {
//Wrapping to RestError won't catch JsonMappingException
}
}
The stacktrace of the exception on server side says it's cause is a org.glassfish.jersey.server.internal.process.MappableException:
Upvotes: 2
Views: 1684
Reputation: 1597
According to the Jersey documentation the Auto Discovery feature is enabled by default
Jersey Auto Discoverable
If the jackson-jaxrs-base-2.x.x.jar is present in your classpath both the JsonMappingExceptionMapper and the JsonParseExceptionMapper are automatically registed because ExceptionMappers are additional SPIs recognized by Jersey. Also bothJsonMappingExceptionMapper and JsonParseExceptionMapper are annoteaded with the @Provider annotation.
To disable this Auto Discovery Feature you need to set the FEAUTURE_AUTO_DISCOVERY_DISABLE property. See Jersey Configuring Auto-discovery Mechanism. This way Jackson is not registed anymore.
resourceConfig.property(CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true);
Now register your resources, your ExceptionMapper and the JacksonJaxbJsonProvider (do not register the JacksonFeature.class).
resourceConfig.register(com.organization.resources.InfoResource.class);
resourceConfig.register(com.organization.resources.ThrowableExceptionMapper.class);
resourceConfig.register(com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider.class);
Like this the JsonMappingException will be caught in the ThrowableExceptionMapper class.
This setup worked for me but has the disadvantage that I can't register my resources with a package anymore I am pretty sure there are better ways to reach the goal any improvments are more than welcome
Upvotes: 1