Neel
Neel

Reputation: 303

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.

Upvotes: 20

Views: 14634

Answers (3)

Teo J.
Teo J.

Reputation: 560

In addition to the accepted answer I had to register JsonMappingExceptionMapper with my ResourceConfig and specify bindingPriority = 1 because otherwise it was invoking the default JsonMappingExceptionMapper:

resourceConfig.register(JsonMappingExceptionMapper.class, 1);

Upvotes: 0

mkyong
mkyong

Reputation: 2289

Tested with Jersey 3, Jackson 2.x, and Grizzly HTTP server.

Create an ExceptionMapper as the @Provider to catch the JsonMappingException.

import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.ext.ExceptionMapper;
import jakarta.ws.rs.ext.Provider;

@Provider
public class CustomJsonExceptionMapper
      implements ExceptionMapper<JsonMappingException> {

  private static final ObjectMapper mapper = new ObjectMapper();

  @Override
  public Response toResponse(JsonMappingException exception) {

      ObjectNode json = mapper.createObjectNode();
      //json.put("error", exception.getMessage());
      json.put("error", "json mapping error");
      return Response.status(Response.Status.BAD_REQUEST)
              .entity(json.toPrettyString())
              .build();
  }

}

Register the above exception mapper in ResourceConfig

public static HttpServer startHttpServer() {

       final ResourceConfig config = new ResourceConfig();
       config.register(YourResource.class);
      
       // custom ExceptionMapper
       config.register(CustomJsonExceptionMapper.class);

       return GrizzlyHttpServerFactory.createHttpServer(BASE_URI, config);
}

Refer to this Jersey and Jackson example.

Upvotes: 0

itzg
itzg

Reputation: 1111

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

Upvotes: 25

Related Questions