我定义了一个数据类型及其 API:
public class DataType {
@Column
private String name;
}
// API is:
public class DataTypeAPI {
@POST
@Path("/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ManagedAsync
public void createDataType(
final DataType dataType,
) {
...
asyncResponse.resume(Response.status(Response.Status.CREATED)
.entity(dataType)
.build());
}
}
{
"name": "xxx"
}
如果我摆姿势一切都很好
但是当我发布时{ "name1": "xxx" }
,我得到了以下text/plain
回复:
Unrecognized field "name1" (class com.xxx.datatypes.DataType), not marked as ignorable (1 known properties: "name"])
at [Source: org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream@526e34b1; line: 2, column: 15] (through reference chain: com.xxx.datatypes.DataType["name1"])
我更喜欢将上述错误转换为 JSON 响应。但是事件我添加了以下异常映射器,它没有返回 JSON 响应。
@Provider
public class GenericExceptionMapper implements ExceptionMapper<Throwable> {
public Response toResponse(Throwable ex) {
System.out.println("GenericExceptionMapper");
ex.printStackTrace();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(new ErrorBody(500, ex.getMessage()))
.type(MediaType.APPLICATION_JSON)
.build();
}
}
为什么我上面的异常映射器无法捕获球衣解析错误。有人可以向我解释吗?谢谢
更新
我有两个问题:
1、如何做出响应来application/json
代替text/plain
?
2、为什么我的异常映射器没有捕捉到引发的异常并将其映射到json响应?
更新
我添加了以下映射器:
public class JsonMappingExceptionMapper implements ExceptionMapper<JsonMappingException> {
public Response toResponse(JsonMappingException ex) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(new ErrorBody(500, ex.getMessage()))
.type(MediaType.APPLICATION_JSON)
.build();
}
}
现在,我可以得到 json 响应:
{
"code": 500,
"message": "Unrecognized field \"name1\" (class com.xxx.datatypes.DataType), not marked as ignorable (1 known properties: \"name\"])\n at [Source: org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream@1d8cd12a; line: 2, column: 15] (through reference chain: class com.xxx.datatypes.DataType[\"name1\"])"
}
我还有两个问题:
1、为什么我的通用异常映射器无法捕获它。
2、 json映射异常映射器贴出时无法映射如下异常(逗号,添加测试用)Unexpected character ('}' (code 125)): was expecting double-quote to start field name
at [Source: org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream@7615743c; line: 3, column: 2]
{"name": "xxxx",}