java - 如何在 @NotBlank(message="...") 注释的自定义异常包装器中设置错误消息?
问题描述
我正在尝试创建一个@ControllerAdvice
当前处理MethodArgumentNotValidException
异常的类。我为具有errorMessage
andstatusCode
属性的响应创建了一个异常包装器。
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
解决方案
尝试这个。
@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
推荐阅读
- javascript - 如何使用javascript过滤对象数组中的对象数组?
- wpf - 用计算的比率绑定 2 个文本框
- reactjs - 为什么测试会影响组件中未使用的减速器?
- javascript - 将数组中对象和嵌套对象的键值对重新组合到新数组中
- webview2 - webView.EnsureCoreWebView2Async(null) 给出一个异常类未注册
- django - Django:像 blog.user.username 这样的表达式是否在 Django 中执行了额外的数据库操作?
- python - 在 ndarrays 中查找最接近零的值
- json - 使用连接运行 json 的正确包?
- java - 获取异常“java.lang.NoSuchMethodError:org.openqa.selenium.WebElement.getDomAttribute(Ljava/lang/String;)Ljava/lang/String;” 在硒 4
- javascript - Javascript 如果可以打开应用程序的自定义 URL,而不是切换显示:阻止