处理 Controller 数据绑定、数据校验的异常
@Data
public class Dog {
@NotNull(message = "{Dog.id.non}", groups = {Update.class})
@Min(value = 1, message = "{Dog.age.lt1}", groups = {Update.class})
private Long id;
@NotBlank(message = "{Dog.name.non}", groups = {Add.class, Update.class})
private String name;
@Min(value = 1, message = "{Dog.age.lt1}", groups = {Add.class, Update.class})
private Integer age;
}
@PatchMapping(value = "")
AppResponse update(@Validated(Update.class) @RequestBody Dog dog){
AppResponse resp = new AppResponse();
// 执行业务
Dog newDog = dogService.update(dog);
// 返回数据
resp.setData(newDog);
return resp;
}
/**
*
* @ControllerAdvice + @ExceptionHandler 实现全局的 Controller 层的异常处理
*/
@ControllerAdvice
public class GlobalExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 处理所有不可知的异常
* @param e
* @return
*/
@ExceptionHandler(Exception.class)
@ResponseBody
AppResponse handleException(Exception e){
LOGGER.error(e.getMessage(), e);
AppResponse response = new AppResponse();
response.setFail("操作失败!");
return response;
}
/**
* 处理所有业务异常
* @param e
* @return
*/
@ExceptionHandler(BusinessException.class)
@ResponseBody
AppResponse handleBusinessException(BusinessException e){
LOGGER.error(e.getMessage(), e);
AppResponse response = new AppResponse();
response.setFail(e.getMessage());
return response;
}
/**
* 处理所有接口数据验证异常
* @param e
* @return
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
AppResponse handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
LOGGER.error(e.getMessage(), e);
AppResponse response = new AppResponse();
response.setFail(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
return response;
}
}
转载于:https://blog.51cto.com/xiaok007/2286713