java Jersey/Jackson:如何捕获 json 映射异常?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28231323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 13:13:03  来源:igfitidea点击:

Jersey/Hymanson: how to catch json mapping exception?

javajsonjersey

提问by Neel

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

如果输入 json 无效,我想在我的 Restful 服务中捕获 json 映射异常。

It throws org.codehaus.Hymanson.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.

它 throws org.codehaus.Hymanson.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();
    }
}

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

一切正常,但如果 json 主体格式不正确,则会引发JsonMappingException异常。我想捕捉这个异常。

回答by itzg

What finally worked for me was to declare an ExceptionMapperprovider for JsonMappingException, such as

最终对我有用的是声明一个ExceptionMapper提供程序JsonMappingException,例如

import org.codehaus.Hymanson.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();
    }
}