泽西/杰克逊:如何捕捉json映射异常?

时间:2015-01-30 07:38:25

标签: java json jersey

我想在我的restful服务中捕获json映射异常,以防输入json无效。

它会抛出org.codehaus.jackson.map.JsonMappingException,但我不知道如何或在何处捕获此异常。我想捕获此异常并发回适当的错误响应。

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

一切正常,但如果json体形状不好,则抛出JsonMappingException异常。我想抓住这个例外。

2 个答案:

答案 0 :(得分:19)

最终对我有用的是为ExceptionMapper宣布JsonMappingException提供商,例如

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

答案 1 :(得分:0)

使用 Jersey 3、Jackson 2.x 和 Grizzly HTTP 服务器进行测试。

创建一个 ExceptionMapper 作为 @Provider 来捕捉 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();
  }

}

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

参考此Jersey and Jackson example