Jersey Exception mappers not working when jackson deserialization fails

后端 未结 5 2009
借酒劲吻你
借酒劲吻你 2020-12-29 06:57

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

5条回答
  •  天涯浪人
    2020-12-29 07:54

    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.

提交回复
热议问题