我可以在 spring 引导 Web 应用程序中获取所有验证错误吗?

Can I get all validation errors in spring boot web application?

我有一个如下所示的 pojo(请假设有一个控制器和其余代码。应用程序在 Spring 引导中):

@Getter  @Setter
@AllArgsConstructor  @NoArgsConstructor
public class User  {
    @NotBlank(message = "userName is blank")
    private String userName;

    @NotBlank(message = "secretKey is blank")
    private String secretKey;
}

并定义了一个用 @ControllerAdvice 注释的 ExceptionHandler class 并定义了如下方法:

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    protected ResponseEntity<ErrorResponse> handleMethodArgNotValidException(MethodArgumentNotValidException ex,Locale locale) {
        // code to handle exception.
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = {WebExchangeBindException.class})
    protected ResponseEntity<ErrorResponse> handleException(WebExchangeBindException ex, Locale locale) {
        // code to handle exception.
    }

但在这种情况下,即使两个字段都有验证错误,客户端也只会得到一个。

我想问一下,有什么方法可以列出此端点响应中的所有验证错误?

curl --location --request POST 'localhost/api/login' \
--header 'Content-Type: application/json' \
--data-raw '{
    "userName": null,
    "secretKey": null
}'

您可以从MethodArgumentNotValidException获取BindingResult,然后根据所有被拒绝的字段撰写消息,例如:

@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    protected ResponseEntity<ErrorResponse> handleMethodArgNotValidException(MethodArgumentNotValidException ex, Locale locale) {

        String errorMessage = ex.getBindingResult()
                .getFieldErrors()
                .stream()
                .map(fieldError -> fieldError.getField() + ": " + fieldError.getDefaultMessage())
                .collect(Collectors.joining("; "));

        // put errorMessage into ErrorResponse
        // return ResponseEntity<ErrorResponse>
    }
}

可能的消息输出示例:

{
    "timestamp": "2022-01-28T17:18:53.1738558+03:00",
    "status": 400,
    "error": "BadRequest",
    "errorMessage": "userName: userName is blank; secretKey: secretKey is blank"
}