I am using Jersey 2.10 with Jackson serialization/deserialization feature in my REST API.
My idea is to make my REST API to always return a standard JSON error resp
I tested it with an exception mapper like below:
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import com.fasterxml.jackson.core.JsonProcessingException;
@Provider
public class JsonProcessingExceptionMapper implements ExceptionMapper{
public static class Error {
public String key;
public String message;
}
@Override
public Response toResponse(JsonProcessingException exception) {
Error error = new Error();
error.key = "bad-json";
error.message = exception.getMessage();
return Response.status(Status.BAD_REQUEST).entity(error).build();
}
}
and it worked.
Update: changed JsonParseException to JsonProcessingException (more general)
Update2: In order to avoid registering the unwanted mappers replace
register(org.glassfish.jersey.jackson.JacksonFeature.class);
with
register(com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider.class);
Look at the source code of JacksonFeature and you'll understand what's happening.