首页 > 解决方案 > 如何在不同的 Jackson 反序列化失败时自定义 HTTP 响应消息?

问题描述

我有获取 JSON 和 Jackson 2.10的 Spring Web @PostMapping端点。应该将它绑定到@RequestBody DTO,里面有几个枚举。如果为枚举字段传递了无效的字符串值,我得到

InvalidFormatException: Cannot deserialize value of type A from String "foo": not one of the values accepted for Enum class: A

这是很好的场景,但我的 400 Bad Request 里面没有任何有意义的消息。

如何为每个失败的枚举提供 400 中的自定义响应消息?

例子:

我可以使用一些 javax.validation 注释,但我找不到正确的注释。

标签: javajsonspring-mvcjackson

解决方案


Jackson 转换器类处理InvalidFormatException并抛出一个通用的HttpMessageNotReadableException. 所以要自定义响应错误信息,我们需要处理HttpMessageNotReadableException而不是InvalidFormatException.

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler({HttpMessageNotReadableException.class})
@ResponseBody
public String handleHttpMessageNotReadableException(HttpMessageNotReadableException ex) {
    if(ex.getMessage().contains("Cannot deserialize value of type A")){
        return "Binding failed. Allowed values are A, B and C";
    } else if(ex.getMessage().contains("Cannot deserialize value of type B")){
        return "Binding failed. Allowed values are 1, 2 and 3";
    }
    return ex.getMessage();
}

推荐阅读