如何在反序列化失败时自定义错误响应 [英] How to customize error response when deserializing failed

查看:663
本文介绍了如何在反序列化失败时自定义错误响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个jaxrs端点服务,在我自己的 ResourceConfig 我注册了一个 ExceptionMapper ,所以当出现错误时,它将返回JSON {errorEnum:something} 。服务类看起来像这样。

I have a jaxrs endpoint service, in my own ResourceConfig I register an ExceptionMapper, so when somewhere wrong happened, it will return a JSON { errorEnum: "something" }. The service class looks like this.

@POST
@Path("/query")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response query(final QueryDefinition queryDefinition) {
    ...
}

但是,在我的有效载荷中,有一个字段是Enum。如果任何用户在该字段中输入错字,则错误消息将为

However, in my payload, there is a field which is Enum. If any user made a typo in that field, the error message will be

Can not deserialize value of type FIELD from String "AAA": value not
one of declared Enum instance names: [AAA, BBB, CCC]  at [Source:
org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream@62ac814;
line: 15, column: 17] (through reference chain:
QueryDefinition["FIELD"])

我试图使用自定义的EnumDeserializer,

I tried to use the customized EnumDeserializer,

public class EnumDeserializer extends JsonDeserializer<Enum   {
    @Override
    public Dimensions deserialize(JsonParser jp, DeserializationContext deserializationContext) throws IOException,
JsonProcessingException {
        JsonNode node = jp.getCodec().readTree(jp);
        String enumName = node.textValue();
        Enum e = Enums.fromString(enumName);
        if (e != null) { return e; }
        throw new CustomizedException("Not supported Enum");
    } }

然后响应变为不支持Enum(通过参考链:QueryDefinition [FIELD]),这仍然不是我想要的。

But then the response becomes Not supported Enum (through reference chain: QueryDefinition["FIELD"]), which is still not what I want.

推荐答案

Jackson提供商已经 ExceptionMapper s 1 ,只会在捕获到异常时返回异常消息。如果需要,您可以为这些异常创建自己的 ExceptionMapper ,即 JsonParseException JsonMappingException ,只返回你想要的消息。然后只需使用Jersey应用程序注册这些映射器。这应该覆盖杰克逊注册的那些。

The Jackson provider already has ExceptionMappers1 that will just return the exception message when an exception is caught. If you want, you can just create your own ExceptionMapper for these exceptions, i.e. JsonParseException and JsonMappingException, and just return the message you want. Then just register those mappers with the Jersey application. This should override the ones registered by Jackson.

你的异常映射器不起作用的原因是因为来自Jackson的那些更具体。总是会调用更具体的一个。

The reason your exception mapper doesn't work is because the ones from Jackson are more specific. The more specific one always gets invoked.

1 - 即 JsonParseExceptionMapper JsonMappingExceptionMapper

这篇关于如何在反序列化失败时自定义错误响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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