泽西/jackson:如何捕捉json映射exception?
我希望在我的restful服务中捕获json映射exception,以防输入json无效。
它抛出org.codehaus.jackson.map.JsonMappingException
,但我不知道如何或在何处捕获此exception。 我想捕获此exception并发回适当的错误响应。
@JsonInclude(JsonInclude.Include.NON_NULL) @Generated("org.jsonschema2pojo") @JsonPropertyOrder({ "name", "id" }) public class Customer { @JsonProperty("name") private String name; @JsonProperty("id") private String id; } 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 body没有很好地形成,那么它会抛出JsonMappingException
exception。 我想抓住这个例外。
最终对我JsonMappingException
是为JsonMappingException
声明一个ExceptionMapper
提供程序,例如
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 { @Override public Response toResponse(JsonMappingException exception) { return Response.status(Response.Status.BAD_REQUEST).build(); } }