Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
488 views
Welcome To Ask or Share your Answers For Others

1 Answer

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();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...