我想在我的静态服务中捕获json映射异常,以防输入json无效。
它抛出org.codehaus.jackson.map.JsonMappingException,但我不知道如何或在何处捕获此异常。我想捕获此异常并发送回适当的错误响应。
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异常。我想抓住这个例外。
JsonMappingException
最终对我有用的是声明的ExceptionMapper提供者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<JsonMappingException> { @Override public Response toResponse(JsonMappingException exception) { return Response.status(Response.Status.BAD_REQUEST).build(); } }