RS响应HTTP状态500而不是HTTP状态400
有时JAR-RS客户端发送错误的语法请求体。 服务器应该响应HTTP状态400(错误请求),但它响应HTTP状态500(内部服务器错误)。
码:
JAX-B模型类:
@XmlRootElement(namespace = "http://www.test.com/test")
@XmlAccessorType(value = XmlAccessType.FIELD)
public class TestModel {
@XmlElement
private String id;
}
JAX-RS资源类:
@Path("test")
public class TestResource {
@POST
@Consumes(MediaType.APPLICATION_JSON)
public void create(TestModel testModel) {
// some code
}
}
CXF配置:
<jaxrs:server address="/rest" id="test" staticSubresourceResolution="true">
<jaxrs:serviceBeans>
<ref bean="testResource" />
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider" />
</jaxrs:providers>
</jaxrs:server>
例:
请求正文:
{"id2": "test"}
id2
是错误的,所以客户端应该得到HTTP状态400,但它获得HTTP状态500。
服务器日志:
Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "id2" (class test.TestModel), not marked as ignorable (one known property: "id"])
at [Source: org.apache.cxf.transport.http.AbstractHTTPDestination$1@6f30793d; line: 1, column: 10] (through reference chain: test.TestModel["id2"])
at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:51)
at com.fasterxml.jackson.databind.DeserializationContext.reportUnknownProperty(DeserializationContext.java:839)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:1045)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1352)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownVanilla(BeanDeserializerBase.java:1330)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:264)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:125)
at com.fasterxml.jackson.databind.ObjectReader._bind(ObjectReader.java:1470)
at com.fasterxml.jackson.databind.ObjectReader.readValue(ObjectReader.java:912)
at com.fasterxml.jackson.jaxrs.base.ProviderBase.readFrom(ProviderBase.java:811)
at org.apache.cxf.jaxrs.utils.JAXRSUtils.readFromMessageBodyReader(JAXRSUtils.java:1343)
at org.apache.cxf.jaxrs.utils.JAXRSUtils.readFromMessageBody(JAXRSUtils.java:1294)
at org.apache.cxf.jaxrs.utils.JAXRSUtils.processParameter(JAXRSUtils.java:826)
at org.apache.cxf.jaxrs.utils.JAXRSUtils.processParameters(JAXRSUtils.java:789)
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.processRequest(JAXRSInInterceptor.java:212)
... 68 more
有没有一种方法可以配置Jackson和/或CXF,以便在没有模式验证或bean验证的情况下为错误的语法请求主体返回HTTP状态400?
问题是没有映射到响应的ExceptionMapper
(通过ExceptionMapper
的方式)转化为一般的服务器错误响应,因为运行时不知道如何处理异常。
jackson-jaxrs-provider
模块具有ExceptionMapper
来处理Jackson基本异常类JsonMappingException
和JsonParseException
。 映射器分别是JsonMappingExceptionMapper
和JsonParseExceptionMapper
。 这些映射器将异常映射到400响应以及作为响应主体的异常消息。 如果你不喜欢这个响应体,你可以编写你自己的映射器。
上一篇: RS response with HTTP status 500 instead of HTTP status 400