控制器
@RequestMapping("/test")
public void test(@Validated @RequestBody User user) {
System.out.println(user);
}
实体
@Data
public class User {
private Long id;
@NotBlank(message = "name不为空")
private String name;
@NotBlank(message = "slug不为空")
private String slug;
}
校验抛出MethodArgumentNotValidException
异常,
如何像org.springframework.validation.BindException
可以优雅的打出异常信息呢?
@ControllerAdvice
public class MyException {
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
public void handler(MethodArgumentNotValidException e) {
System.out.println(e.getMessage());
}
@ExceptionHandler(BindException.class)
@ResponseBody
public void handler2(BindException e) {
StringBuilder sb = new StringBuilder();
List<FieldError> errors = e.getFieldErrors();
for (FieldError error : errors) {
sb.append(error.getField()).append(error.getDefaultMessage());
}
System.out.println(sb.toString());
}
}
你是想给
response
里面写一些东西吗?可以参考实现ResponseEntityExceptionHandler
,你想怎么定义都行。