1、全局异常处理的原因
为了使我们的代码更容易维护,同时给用户最好的用户体验,有必要对系统中可能出现的异常进行处理。
2、spring提供了@ControllerAdvice注解和@ExceptionHandler可以很好的在控制层对异常进行统一处理
代码如下
(1)先自己定义一个异常类
@Getter
public class CommonException extends Exception {
private ResultCode resultCode;
public CommonException(ResultCode resultCode) {
this.resultCode = resultCode;
}
}
(2)实现全局异常处理类
@ControllerAdvice
public class BaseExceptionHandler {
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Result error(HttpServletRequest request, HttpServletResponse response, Exception e) {
if (e.getClass() == CommonException.class) {
CommonException ce = (CommonException) e;
return new Result(ce.getResultCode());
}
return new Result(ResultCode.SERVER_ERROR);
}
@ExceptionHandler(value = AuthorizationException.class)
@ResponseBody
public Result error(HttpServletRequest request, HttpServletResponse response, AuthorizationException e) {
return new Result(ResultCode.UNAUTHORISE);
}
}
(3)在自己需要抛出异常的类中直接使用
throw new CommonException(ResultCode.UNAUTHORISE)
![在这里插入图片描述](https://img-blog.csdnimg.cn/e38db205014a45238415679c93e6adfb.png)
3、微服务架构时,放在Common模块时候,其他模块引入记得在启动类上开启包扫描,同时要扫描到该配置类