泽西/杰克逊:如何捕捉json映射异常? [英] Jersey/Jackson: how to catch json mapping exception?

查看:173
本文介绍了泽西/杰克逊:如何捕捉json映射异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

它抛出 org.codehaus.jackson.map.JsonMappingException ,但我不知道如何或在哪里抓住这个例外。我想捕获此异常并发回适当的错误响应。

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

一切正常,但如果json身体不好然后它会抛出 JsonMappingException 异常。我想抓住这个例外。

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

推荐答案

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

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

这篇关于泽西/杰克逊:如何捕捉json映射异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆