java - 如何在不同的 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 中的自定义响应消息?
例子:
交易字段的有效值为 BUY 和 SELL
组字段的有效值为 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();
}
推荐阅读
- mongodb - 在 Mongo - 如何从具有特定 id 的嵌套数组中删除
- html - 如何将 div 作为滚动条?
- amazon-web-services - 使用复制删除 S3 存储桶
- python - 在谷歌云函数中使用opencv Python从视频中提取帧
- python - Beautifulsoup 通过可变 URL 循环
- python - Bot 在服务器上看不到成员
- mysql - MYSQL PRIMARY CHAR KEY 的最大最佳大小是多少
- android - 由于 Android 中的数据存储迁移,应用升级后应用崩溃
- python - 如何访问项目根文件夹中的文件?
- c++ - 在 C++ 中创建具有不同参数的多个构造函数的正确方法?