我有 Spring Web @PostMapping 端点,它获取 JSON 和 Jackson 2.10。应该将其绑定(bind)到 @RequestBody DTO,其中包含几个枚举。如果为 Enum 字段传递了无效的字符串值,我会得到 p>
InvalidFormatException: Cannot deserialize value of type A from String "foo": not one of the values accepted for Enum class: A
这是很好的场景,但我的 400 错误请求内部没有任何有意义的消息。
如何为每个失败的枚举提供 400 中的自定义响应消息?
示例:
交易字段的有效值为“买入”和“卖出”
组字段的有效值为 A、B、C 和 D
我也许可以使用一些 javax.validation 注释,但我找不到合适的注释。
最佳答案
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();
}
关于java - 如何针对不同的 Jackson 反序列化失败创建自定义 HTTP 响应消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62054406/