Implement an ExceptionMapper
for JsonParseException
. It will allow you to map the given exception to a response. See the example below:
@Provider
public class JsonParseExceptionMapper implements ExceptionMapper<JsonParseException> {
@Override
public Response toResponse(JsonParseException exception) {
return Response.status(Response.Status.BAD_REQUEST)
.entity("Cannot parse JSON")
.type(MediaType.TEXT_PLAIN)
.build();
}
}
And then register it with a binding priority in your ResourceConfig
subclass (see notes):
@ApplicationPath("api")
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
register(JsonParseExceptionMapper.class, 1);
}
}
If you are not using a ResourceConfig
subclass, you can annotate the ExceptionMapper
with @Priority
(see notes):
@Provider
@Priority(1)
public class JsonParseExceptionMapper implements ExceptionMapper<JsonParseException> {
...
}
Note 1: You may also find it helpful to create another ExceptionMapper
for JsonMappingException
.
Note 2: Giving a priority to your own ExceptionMapper
s is particularly useful if you have the JacksonFeature
registered and you want to override the behavior of JsonParseExceptionMapper
and JsonMappingExceptionMapper
that come with the jackson-jaxrs-json-provider
module. See this answer for further details.