JSR 303校验,如何优雅的报异常

image.png

控制器

@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());

    }

}
阅读 1.5k
1 个回答

你是想给response里面写一些东西吗?可以参考实现 ResponseEntityExceptionHandler,你想怎么定义都行。

protected ResponseEntity<Object> handleBindException(
            BindException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        return getObjectResponseEntity(ex, headers, status, request);
    }

    private ResponseEntity<Object> getObjectResponseEntity(BindException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
        List<String> collect =
                fieldErrors
                        .stream()
                        .map(DefaultMessageSourceResolvable::getDefaultMessage)
                        .collect(Collectors.toList());
        return handleExceptionInternal(ex, Msg.badRequest().add("errMsg", StringUtils.join(collect, ",")), headers, status, request);
    }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏