利用SpringAOP实现统一异常处理
SpringBoot项目统一异常处理方案(一)
SpringBoot项目统一异常处理方案(二)
第三种:SpringAOP统一拦截
通过AOP(面向切面编程)
的方式,统一对 Controller 层的所有类的方法进行代理,所有被代理的方法都会经过SysControllerAspect
的处理,这样即做到了异常的统一捕获处理。如下代码示例:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23@Component @Aspect public class SysControllerAspect { private static final Logger LOG = LoggerFactory.getLogger(SysAspect.class); @Pointcut("execution(* com.bin.controller..*(..))") public void pointCut(){} @Around("pointCut()") public Object doExceptionAdvice(ProceedingJoinPoint point) throws Throwable { Object proceed; try { proceed = point.proceed(); } catch (Exception e) { LOG.error("参数信息:" + JSON.toJSONString(point.getArgs()), e); if (e instanceof BusinessException) { return Playload.error(RespCode.BUSINESS_EX.getCode(), e.getMessage()); } else { return Playload.error(RespCode.OTHER_EX.getCode(), e.getMessage()); } } return proceed; } }
总结步骤如下:
1、创建SysControllerAspect
,加上@Aspect
注解标识为切面类,并将它注册到IOC容器中管理
2、定义一个pointCut(切点)
,定义切点表达式@Pointcut("execution(* com.bin.controller..*(..))")
,这里的含义是:匹配到 com.bin.controller 包和子包下的所有方法
3、定义一个 doExceptionAdvice(增强方法)
,并声明为@Around("pointCut()")
,作用是将pointCut()
匹配到的所有方法进行环绕增强 (环绕增强即是在目标方法执行前和执行后要做的操作),这里做的操作即是对目标方法进行异常捕获
4、最终根据异常类型去匹配到你定义的业务异常BusinessException
或者其他异常,进行不同结果的返回。
注:这种通过AOP的方式同时还很方便的进行接口的执行时间记录,SpringAOP还可以做其他很多事情比如 参数校验,缓存控制,权限验证,事务管理 等等…
最后
以上就是要减肥煎饼最近收集整理的关于SpringBoot项目统一异常处理方案(三)的全部内容,更多相关SpringBoot项目统一异常处理方案(三)内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复