在spring中手寫全局異常攔截器
為什么要重復(fù)造輪子
你可能會(huì)問,Spring已經(jīng)自帶了全局異常攔截,為什么還要重復(fù)造輪子呢?
這是個(gè)好問題,我覺得有以下幾個(gè)原因
裝逼 Spring的全局異常攔截只是針對(duì)于Spring MVC的接口,對(duì)于你的RPC接口就無能為力了 無法定制化 除了寫業(yè)務(wù)代碼,我們其實(shí)還能干點(diǎn)別的事我覺得上述理由已經(jīng)比較充分的解答了為什么要重復(fù)造輪子,接下來就來看一下怎么造輪子
造個(gè)什么樣的輪子?
我覺得全局異常攔截應(yīng)該有如下特性
使用方便,最好和spring原生的使用方式一致,降低學(xué)習(xí)成本 能夠支持所有接口 調(diào)用異常處理器可預(yù)期,比如說定義了RuntimeException的處理器和Exception的處理器,如果這個(gè)時(shí)候拋出NullPointException,這時(shí)候要能沒有歧義的選擇預(yù)期的處理器如何造輪子?
由于現(xiàn)在的應(yīng)用基本上都是基于spring的,因此我也是基于SpringAop來實(shí)現(xiàn)全局異常攔截
首先先定義幾個(gè)注解
@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Componentpublic @interface ExceptionAdvice {}@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface ExceptionHandler { Class<? extends Throwable>[] value();}@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface ExceptionIntercept {}
@ExceptionAdvice 的作用是標(biāo)志定義異常處理器的類,方便找到異常處理器
@ExceptionHandler 的作用是標(biāo)記某個(gè)方法是處理異常的,里面的值是能夠處理的異常類型
@ExceptionIntercept 的作用是標(biāo)記需要異常攔截的方法
接下來定義統(tǒng)一返回格式,以便出現(xiàn)錯(cuò)誤的時(shí)候統(tǒng)一返回
@Datapublic class BaseResponse<T> { private Integer code; private String message; private T data; public BaseResponse(Integer code, String message) { this.code = code; this.message = message; }}
然后定義一個(gè)收集異常處理器的類
public class ExceptionMethodPool { private List<ExceptionMethod> methods; private Object excutor; public ExceptionMethodPool(Object excutor) { this.methods = new ArrayList<ExceptionMethod>(); this.excutor = excutor; } public Object getExcutor() { return excutor; } public void add(Class<? extends Throwable> clazz, Method method) { methods.add(new ExceptionMethod(clazz, method)); } //按序查找能夠處理該異常的處理器 public Method obtainMethod(Throwable throwable) { return methods.stream().filter(e -> e.getClazz().isAssignableFrom(throwable.getClass())).findFirst().orElseThrow(() ->new RuntimeException('沒有找到對(duì)應(yīng)的異常處理器')).getMethod(); } @AllArgsConstructor @Getter class ExceptionMethod { private Class<? extends Throwable> clazz; private Method method; }}
ExceptionMethod 里面有兩個(gè)屬性
clazz:這個(gè)代表著能夠處理的異常 method:代表著處理異常調(diào)用的方法ExceptionMethodPool 里面按序存放所有異常處理器,excutor是執(zhí)行這些異常處理器的對(duì)象
接下來把所有定義的異常處理器收集起來
@Componentpublic class ExceptionBeanPostProcessor implements BeanPostProcessor { private ExceptionMethodPool exceptionMethodPool; @Autowired private ConfigurableApplicationContext context; @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { Class<?> clazz = bean.getClass(); ExceptionAdvice advice = clazz.getAnnotation(ExceptionAdvice.class); if (advice == null) return bean; if (exceptionMethodPool != null) throw new RuntimeException('不允許有兩個(gè)異常定義類'); exceptionMethodPool = new ExceptionMethodPool(bean); //保持處理異常方法順序 Arrays.stream(clazz.getDeclaredMethods()).filter(method -> method.getAnnotation(ExceptionHandler.class) != null).forEach(method -> { ExceptionHandler exceptionHandler = method.getAnnotation(ExceptionHandler.class); Arrays.stream(exceptionHandler.value()).forEach(c -> exceptionMethodPool.add(c,method));}); //注冊(cè)進(jìn)spring容器 context.getBeanFactory().registerSingleton('exceptionMethodPool',exceptionMethodPool); return bean; }}
ExceptionBeanPostProcessor 通過實(shí)現(xiàn)BeanPostProcessor 接口,在bean初始化之前,把所有異常處理器塞進(jìn) ExceptionMethodPool,并把其注冊(cè)進(jìn)Spring容器
然后定義異常處理器
@Componentpublic class ExceptionProcessor { @Autowired private ExceptionMethodPool exceptionMethodPool; public BaseResponse process(Throwable e) { return (BaseResponse) FunctionUtil.computeOrGetDefault(() ->{ Method method = exceptionMethodPool.obtainMethod(e); method.setAccessible(true); return method.invoke(exceptionMethodPool.getExcutor(),e); },new BaseResponse(0,'未知錯(cuò)誤')); }}
這里應(yīng)用了我自己通過函數(shù)式編程封裝的一些語(yǔ)法糖,有興趣的可以看下
最后通過AOP進(jìn)行攔截
@Aspect@Componentpublic class ExceptionInterceptAop { @Autowired private ExceptionProcessor exceptionProcessor; @Pointcut('@annotation(com.example.exception.intercept.ExceptionIntercept)') public void pointcut() { } @Around('pointcut()') public Object around(ProceedingJoinPoint point) { return computeAndDealException(() -> point.proceed(),e -> exceptionProcessor.process(e)); } public static <R> R computeAndDealException(ThrowExceptionSupplier<R> supplier, Function<Throwable, R> dealFunc) { try { return supplier.get(); } catch (Throwable e) { return dealFunc.apply(e); } } @FunctionalInterface public interface ThrowExceptionSupplier<T> { T get() throws Throwable; }}
到這里代碼部分就已經(jīng)完成了,我們來看下如何使用
@ExceptionAdvicepublic class ExceptionConfig { @ExceptionHandler(value = NullPointerException.class) public BaseResponse process(NullPointerException e){ return new BaseResponse(0,'NPE'); } @ExceptionHandler(value = Exception.class) public BaseResponse process(Exception e){ return new BaseResponse(0,'Ex'); } }@RestControllerpublic class TestControler { @RequestMapping('/test') @ExceptionIntercept public BaseResponse test(@RequestParam('a') Integer a){ if (a == 1){ return new BaseResponse(1,a+''); } else if (a == 2){ throw new NullPointerException(); } else throw new RuntimeException(); }}
我們通過@ExceptionAdvice標(biāo)志定義異常處理器的類,然后通過@ExceptionHandler標(biāo)注處理異常的方法,方便收集
最后在需要異常攔截的方法上面通過@ExceptionIntercept進(jìn)行異常攔截
我沒有使用Spring那種匹配最近父類的方式尋找匹配的異常處理器,我覺得這種設(shè)計(jì)是一個(gè)敗筆,理由如下
代碼復(fù)雜 不能一眼看出要去調(diào)用哪個(gè)異常處理器,尤其是定義的異常處理器非常多的時(shí)候,要是弄多個(gè)定義類就更不好找了,可能要把所有的處理器看完才知道應(yīng)該調(diào)用哪個(gè)出于以上考慮,我只保留了一個(gè)異常處理器定義類,并且匹配順序和方法定義順序一致,從上到下依次匹配,這樣只要找到一個(gè)能夠處理的處理器,那么就知道了會(huì)如何調(diào)用
原創(chuàng)不易,如果覺得對(duì)你有幫助,麻煩點(diǎn)個(gè)贊!
我會(huì)不定期分享一些有意思的技術(shù),點(diǎn)個(gè)關(guān)注不迷路-。 -
以上就是在spring中手寫全局異常攔截器的詳細(xì)內(nèi)容,更多關(guān)于spring 全局異常攔截的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. CSS hack用法案例詳解2. css進(jìn)階學(xué)習(xí) 選擇符3. 使用純HTML的通用數(shù)據(jù)管理和服務(wù)4. 使用css實(shí)現(xiàn)全兼容tooltip提示框5. 低版本IE正常運(yùn)行HTML5+CSS3網(wǎng)站的3種解決方案6. CSS Hack大全-教你如何區(qū)分出IE6-IE10、FireFox、Chrome、Opera7. css代碼優(yōu)化的12個(gè)技巧8. 告別AJAX實(shí)現(xiàn)無刷新提交表單9. HTML DOM setInterval和clearInterval方法案例詳解10. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)
