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

标签 java spring-boot validation exceptionhandler

我有一个如下所示的 pojo(请假设一个 Controller 和其余代码。应用程序位于 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;
}

并定义了一个带有@ControllerAdvice注释的ExceptionHandler类,并定义了一个方法,如下所示:

    @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"
}

关于java - 我可以获得 Spring Boot Web 应用程序中的所有验证错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70894623/

相关文章:

php - CodeIgniter - 表单验证和 POST 数据

java - 执行 JPQL 查询的工具?

java - IBM Redis 数据库 + Spring boot

java - 如何在 Spring Boot 之上编写框架(即编写 Spring Boot 应用程序而不实现某些接口(interface))

javascript - JQuery 验证 : Validating a hidden form (possible bug)

jquery - 验证下拉菜单

java - 参差不齐的数组不允许我有不同的列

java - 无法将日期从 mysql 检索到 JDBC

java - 更改 JTable 中特定行的颜色

java - 需要帮助弄清楚如何在 spring boot java app 中从 yml 加载嵌套列表