java - Display only default message of Spring boot validation - MethodArgumentNotValidException
问题描述
How can i strip down the excessive information from MethodArgumentNotValidException and keep only the required "default message" ??
I am experimenting with Validation annotations- @NotNull, @NotBlank, and @NotEmpty
I have configured a custom error message as below:-
@NotNull(message = "Aaaah !!!! firstname cannot be empty !!!")
private String firtName;
My Exception handler is :-
@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);
}
}
But the exception message i see on swagger is :-
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 !!!]]
I want to see only the default message * [Aaaah !!!! firstname cannot be empty !!!]] * and remove the extra bunkum.
解决方案
I had a similar experience with adjusting the default messages to something more meaningful.
You have to implement a javax.validation.MessageInterpolation interface. From there you'll be able to interpolate your default message.
I used this site as a reference to solve my issue. https://www.baeldung.com/spring-validation-message-interpolation
推荐阅读
- reactjs - 编译为 ES6 而不是 Typescript - JHipster React
- elixir - 从 Phoenix 的第三方客户端访问测试数据库
- cloud - 如何通过API修改经典网络端点的保留时间
- c# - 基于项目变量的构建后事件命令行
- c# - 如何在 asp.net mvc 中使用 ViewData 传递一个整数值,然后使用存储在 ViewData 中的值与视图中的另一个整数值进行比较?
- java - java请求返回无键数组为字符串,需要用realm表示
- python - 熊猫 to_dict() 自定义格式
- java - 如何更快地从 Selenium WebElement 获取值?
- r - 无法将 ggplot2 更新到最新版本
- python - 从笔记列表中匹配关键短语的最佳方法