首页 > 解决方案 > 如何在 @NotBlank(message="...") 注释的自定义异常包装器中设置错误消息?

问题描述

我正在尝试创建一个@ControllerAdvice当前处理MethodArgumentNotValidException异常的类。我为具有errorMessageandstatusCode属性的响应创建了一个异常包装器。

public class ExceptionBodyResponse {
   private String exceptionMessage;
   private int statusCode;
}

@ControllerAdvice

@ControllerAdvice
public class DTOExceptionHandler {

   @ExceptionHandler(MethodArgumentNotValidException.class)
   @ResponseBody
   public ExceptionBodyResponse handleInvalidArgumentException(MethodArgumentNotValidException exception) {
       return GenericBuilder.of(ExceptionBodyResponse::new)
               .with(ExceptionBodyResponse::setExceptionMessage, exception.getMessage())
               .with(ExceptionBodyResponse::setStatusCode, HttpStatus.BAD_REQUEST.value())
               .build();
      }
}

最后,带有@NotBlank 验证的 DTO 类:

public class RegisterRequestDto {
  @NotBlank
  private String email;

  @NotBlank(message = "Password must not be null!")
  private String password;
}

当我发送具有这种结构的 JSON 时,我期望得到什么响应:

{
  "email":"stack@yahoo.com";
}

是以下错误信息:

{
  "exceptionMessage":"Password must not be null",
  "statusCode":400
}

相反,我得到了这个:

"exceptionMessage": "Validation failed for argument [0] in public packagehere.UserDto packagehere.UserControllerImpl.save(packagehere.RegisterRequestDto): [Field error in object 'registerRequestDto' on field 'password': rejected value [null]; codes [NotBlank.registerRequestDto.password,NotBlank.password,NotBlank.java.lang.String,NotBlank]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [registerRequestDto.password,password]; arguments []; default message [password]]; default message [Password must not be null!]] ",
"statusCode": 400

标签: javaspringspring-bootvalidation

解决方案


尝试这个。

@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class DTOExceptionHandler extends ResponseEntityExceptionHandler{

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(
            final MethodArgumentNotValidException exception,
            final HttpHeaders headers,
            final HttpStatus status,
            final WebRequest request) {
         return GenericBuilder.of(ExceptionBodyResponse::new)
           .with(ExceptionBodyResponse::setExceptionMessage, exception.getMessage())//You can customize message
           .with(ExceptionBodyResponse::setStatusCode, HttpStatus.BAD_REQUEST.value())
           .build();
    }
}

您可以使用ex.getBindingResult().getFieldErrors()获取列表FieldError


推荐阅读