本篇文章给大家分享的是有关使用spring编写一个全局异常拦截器,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
为什么要重复造轮子
你可能会问,Spring已经自带了全局异常拦截,为什么还要重复造轮子呢?
这是个好问题,我觉得有以下几个原因
我觉得上述理由已经比较充分的解答了为什么要重复造轮子,接下来就来看一下怎么造轮子
造个什么样的轮子?
我觉得全局异常拦截应该有如下特性
如何造轮子?
由于现在的应用基本上都是基于spring的,因此我也是基于SpringAop来实现全局异常拦截
首先先定义几个注解
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface ExceptionAdvice { } @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface ExceptionHandler { Class<? extends Throwable>[] value(); } @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface ExceptionIntercept { }