RestControllerAdvice+ExceptionHandler这两个注解的组合,被用作项目的全局异常处理。一旦项目中发生了异常,就会进入使用了RestControllerAdvice注解类中使用了ExceptionHandler注解的方法。
下面是一些项目全局异常的处理
@ControllerAdvice(annotations = {RestController.class, Controller.class} )
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(SQLIntegrityConstraintViolationException.class)
public R<String> excptionHandler(SQLIntegrityConstraintViolationException e){
log.error(e.getMessage());
String message = e.getMessage();
String[] s = message.split(" ");
if (message.contains("Duplicate")){
return R.error(s[2]+"already exists");
}
return R.error("false");
}
@ExceptionHandler(CustomException.class)
public R<String> excptionHandler(CustomException e){
log.error(e.getMessage());
return R.error(e.getMessage());
}
}
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public RespBean ExceptionHandler(Exception e) {
if (e instanceof GlobalException) {
GlobalException exception = (GlobalException) e;
return RespBean.error(exception.getRespBeanEnum());
} else if (e instanceof BindException) {
BindException bindException = (BindException) e;
RespBean respBean = RespBean.error(RespBeanEnum.BIND_ERROR);
respBean.setMessage("参数校验异常:" + bindException.getBindingResult().getAllErrors().get(0).getDefaultMessage());
return respBean;
}
System.out.println("异常信息" + e);
return RespBean.error(RespBeanEnum.ERROR);
}
}
标签:return,RespBean,ExceptionHandler,error,注解,RestControllerAdvice,class
From: https://www.cnblogs.com/xiaoovo/p/17323257.html