@RestControllerAdvice注解 @ExceptionHandler注解

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

本文作者:xiaoovo

本文链接:https://www.cnblogs.com/xiaoovo/p/17323257.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   xiaoovo  阅读(68)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起
🔑