首页 > 解决方案 > 如何处理来自单个 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),然后给出包括这两个字段的错误响应。

有人可以帮我吗?

提前致谢。

标签: javaapiexceptionerror-handlingspring-restcontroller

解决方案


由于验证器不适用于您的情况,您可以在构造函数上使用 @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

}


推荐阅读