spring-boot-starter-validation 中 错误处理怎么写
在spring-boot-starter-validation中,错误处理可以通过以下方式进行:
- 使用@ExceptionHandler注解处理单个异常
@RestControllerAdvice
public class ExceptionController {
@ExceptionHandler(MethodArgumentNotValidException.class)
public Response handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
BindingResult bindingResult = e.getBindingResult();
List<ObjectError> allErrors = bindingResult.getAllErrors();
return Response.error(allErrors.get(0).getDefaultMessage());
}
}
- 使用@Validated注解进行参数校验
@RestController
@RequestMapping("/user")
@Validated
public class UserController {
@PostMapping("/save")
public Response save(@Valid User user) {
// do something
return Response.success();
}
}
- 自定义异常类并使用@ResponseStatus注解
@ResponseStatus(HttpStatus.BAD_REQUEST)
public class BadRequestException extends RuntimeException {
public BadRequestException(String message) {
super(message);
}
}
在方法中抛出自定义异常即可。
@PostMapping("/save")
public Response save(@Valid User user) {
if (StringUtils.isEmpty(user.getName())) {
throw new BadRequestException("用户名不能为空");
}
// do something
return Response.success();
}
原文地址: https://www.cveoy.top/t/topic/bqeL 著作权归作者所有。请勿转载和采集!