仅显示 Spring boot 验证的默认消息 - MethodArgumentNotValidException

use*_*825 6 java spring-boot

我如何从 MethodArgumentNotValidException 中删除过多的信息并仅保留所需的“默认消息”

我正在尝试验证注释 - @NotNull、@NotBlank 和 @NotEmpty

我配置了自定义错误消息,如下所示:-

@NotNull(message = "Aaaah !!!! firstname cannot be empty !!!")
private String firtName;
Run Code Online (Sandbox Code Playgroud)

我的异常处理程序是:-

@RestControllerAdvice
public class ControllerAdviceClass {
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseEntity handleValidationException(MethodArgumentNotValidException ex)
    {
        return new ResponseEntity(ex.getMessage() , HttpStatus.BAD_REQUEST);
    }
}
Run Code Online (Sandbox Code Playgroud)

但我在 swagger 上看到的异常消息是:-

Validation failed for argument [0] in public cosmosdb.User cosmosdb.CosmosController.postResult(cosmosdb.User): 
[Field error in object 'user' on field 'firstName': rejected value [null]; codes [NotNull.user.firstName,NotNull.firstName,NotNull.java.lang.String,NotNull];
 arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.firstName,firstName]; arguments []; default message [firstName]]; 
default message [Aaaah !!!! firstname cannot be empty !!!]] 
Run Code Online (Sandbox Code Playgroud)

我只想看到默认消息* [啊啊啊!!!名字不能为空!!!]] *并删除多余的废话。

小智 3

我也有类似的经历,将默认消息调整为更有意义的内容。

您必须实现 javax.validation.MessageInterpolation 接口。从那里您将能够插入默认消息。

我使用该网站作为解决我的问题的参考。https://www.baeldung.com/spring-validation-message-interpolation

  • 您的意思是:https://www.baeldung.com/global-error-handler-in-a-spring-rest-api? (2认同)