java - 如何处理来自单个 RequestBody 的多个 HttpMessageNotReadableException?
问题描述
对于以下 REST 调用,
@RequestMapping(path = "/speedCalculation", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE }, consumes = { MediaType.APPLICATION_JSON_VALUE })
@ResponseBody
public ResponseEntity<String> processSpeedRequest(@RequestBody SpeedRequest speedRequest) {
以下是我的 POST 请求正文。“speed”是枚举类型,“startDate”是LocalDate类型
"details": {
"speed": "FAST",
"startDate": "2020-01-01"
},
如果给我的请求一个无效的枚举值和无效的日期格式,我只能处理一个 HttpMessageNotReadableException,因为一次只抛出一个。(它实际上抛出了首先遇到的任何东西)。在这种情况下,我只能处理“速度”。
@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<String> handleMessageNotReadableException(Exception ex, WebRequest request) {
// some handling
return new ResponseEntity<>("invalid request------", HttpStatus.BAD_REQUEST);
}
我想捕获请求正文的两个错误(两个 HttpMessageNotReadableException),然后给出包括这两个字段的错误响应。
有人可以帮我吗?
提前致谢。
解决方案
由于验证器不适用于您的情况,您可以在构造函数上使用 @JsonCreator 并在那里进行验证。如果您的验证未通过,则从那里抛出异常。例如,您的请求对象将如下所示:
public class SpeedRequest {
private final SpeedEnum speed;
private final LocalDate date;
@JsonCreator
public SpeedRequest(@JsonProperty("speed") String speed, @JsonProperty("date") String date) {
//Validate fields and throw exception if needed or cast and assign
}
// Methods
}
推荐阅读
- python - 熊猫数据框调整
- spring - 在 Hibernate 初始化期间处理 Spring 数据源暂时不可用
- spring - 测试期间无法加载应用程序上下文,因为表“USERS”已经存在
- c++ - 如何包装 C++
Cython 的图书馆? - c# - 以编程方式在另一台计算机上调用 python 脚本并获得拒绝访问错误
- python-3.x - 用python检测操作系统
- xml - 维基媒体是否支持其他格式来存储数据而不是维基文本?
- malloc - 如何在 malloc 中检测到损坏的双链表错误?
- python - 我需要将文件夹中创建的最后一个 .csv 文件的名称作为 python 脚本的参数传递
- sql-server - 关于 FROM 或 PIVOT 之后的语法的问题。别名是“必须的”吗?