controller的方法添加 @Validated:
public Result<?> add(@Validated @RequestBody WmsSysProduct wmsSysProduct)
.实体类属性添加注解
@NotBlank(message = "测试返回信息")
private String descc;
拦截运行时异常:
```java
@ControllerAdvice
public class SharpBootException extends RuntimeException {
//处理Get请求中 使用@Valid 验证路径中请求实体校验失败后抛出的异常,详情继续往下看代码
@ExceptionHandler(BindException.class)
@ResponseBody
public Result<?> BindExceptionHandler(BindException e) {
String message = e.getBindingResult().getAllErrors().stream().
map(DefaultMessageSourceResolvable::getDefaultMessage).
collect(Collectors.joining(","));
return Result.error(message);
}
//处理请求参数格式错误 @RequestParam上validate失败后抛出的异常是javax.validation.ConstraintViolationException
@ExceptionHandler(ConstraintViolationException.class)
@ResponseBody
public Result<?> ConstraintViolationExceptionHandler(ConstraintViolationException e) {
String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(","));
return Result.error(message);
}
//处理请求参数格式错误 @RequestBody上validate失败后抛出的异常是MethodArgumentNotValidException异常。
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
public Result<?> MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
String message = e.getBindingResult().getAllErrors().stream().
map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(","));
return Result.error(message);
}
}