我可以获得 Spring Boot Web 应用程序中的所有验证错误吗?

asv*_*vni 2 java validation exceptionhandler spring-boot

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

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

    @NotBlank(message = "secretKey is blank")
    private String secretKey;
}
Run Code Online (Sandbox Code Playgroud)

并定义了一个 ExceptionHandler 类,@ControllerAdvice并定义了一个方法,如下所示:

    @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.
    }
Run Code Online (Sandbox Code Playgroud)

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

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

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

Run Code Online (Sandbox Code Playgroud)

Geo*_*vov 6

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

@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>
    }
}
Run Code Online (Sandbox Code Playgroud)

带消息的可能输出示例:

{
    "timestamp": "2022-01-28T17:18:53.1738558+03:00",
    "status": 400,
    "error": "BadRequest",
    "errorMessage": "userName: userName is blank; secretKey: secretKey is blank"
}
Run Code Online (Sandbox Code Playgroud)