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

控制器

@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,你想怎么定义都行。

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

}

以上是 JSR 303校验,如何优雅的报异常 的全部内容, 来源链接: utcz.com/p/944535.html

回到顶部