javajsonjersey

Jersey/Jackson: how to catch json mapping exception?


I would like to catch json mapping exception in my restful service in case input json is not valid.

It throws org.codehaus.jackson.map.JsonMappingException, but I don't how to or where to catch this exception. I want to catch this exception and send back appropriate error response.

@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
@JsonPropertyOrder({
        "name",
        "id"
})
public class Customer {
    @JsonProperty("name")
    private String name;

    @JsonProperty("id")
    private String id;
     <setter/getter code>
}

public class MyService {
   @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public final Response createCustomer(@Context HttpHeaders headers,
            Customer customer) {
        System.out.println("Customer data: " + customer.toString());
        return Response.ok("customer created").build();
    }
}

Everything works fine, but if json body is not well formed then it throws JsonMappingException exception. I want to catch this exception.


Solution

  • What finally worked for me was to declare an ExceptionMapper provider for JsonMappingException, such as

    import org.codehaus.jackson.map.JsonMappingException;
    import org.springframework.stereotype.Component;
    
    import javax.ws.rs.core.Response;
    import javax.ws.rs.ext.ExceptionMapper;
    import javax.ws.rs.ext.Provider;
    
    @Component
    @Provider
    public class JsonMappingExceptionMapper implements ExceptionMapper<JsonMappingException> {
        @Override
        public Response toResponse(JsonMappingException exception) {
            return Response.status(Response.Status.BAD_REQUEST).build();
        }
    }