Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jersey/Jackson: how to catch json mapping exception?

Tags:

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.

like image 769
Neel Avatar asked Jan 30 '15 07:01

Neel


1 Answers

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();
    }
}
like image 134
itzg Avatar answered Oct 29 '22 05:10

itzg