SpringMVC使用@ExceptionHandler注解在Controller中處理異常
異常是每一個(gè)應(yīng)用必須要處理的問題
Spring MVC項(xiàng)目,如果不做任何的異常處理的話,發(fā)生異常后,異常堆棧信息會(huì)直接拋出到頁面。
在Controller寫一個(gè)異常
@GetMapping(value="/hello",produces={"text/html; charset=UTF-8"})
@ResponseBody
public String hello(ModelAndView model){
int c = 100 / 0;
return "<h1>User info</h1>";
}瀏覽器訪問:

用戶體驗(yàn)相當(dāng)不好,所以一般情況下,應(yīng)用必須要想辦法處理異常。
異常處理方式
常見的異常處理方式,無非:
- 應(yīng)用中對(duì)所有可能發(fā)生異常的地方,都try catch,捕獲異常后做相應(yīng)的處理。
- 集中處理異常。
第一種方式顯然不好,一方面是代碼中需要到處都寫try catch,萬一某一段代碼由于程序員的疏忽沒有寫,異常就會(huì)拋出到前臺(tái),很不好。
另外,某些情況下異常是不能捕獲的,比如需要事務(wù)處理的代碼,捕獲異常后會(huì)影響到事務(wù)回滾。
所以,我們還是需要想辦法用第2中方式來處理異常。n多年前曾經(jīng)做過一個(gè)摩托羅拉的項(xiàng)目,其中一項(xiàng)需求就是對(duì)一個(gè)線上系統(tǒng)的異常做處理、不允許異常信息拋出到前臺(tái)頁面。當(dāng)初那個(gè)項(xiàng)目并沒有采用類似SpringMVC的框架,所以最終提出了用filter、在filter中攔截異常的處理方案并且被客戶采納。
其實(shí)SpringMVC的統(tǒng)一異常處理方案和我上面項(xiàng)目中采用的方案非常類似。
SpringMVC的異常處理
Spring MVC提供了如下異常處理選項(xiàng):
- @ExceptionHandle
- @ExceptionHandle + @ControllerAdvice
- 自定義異常處理器HandlerExceptionResolver
@ExceptionHandle
@ExceptionHandle可以作用在Controller中,比如,在上面發(fā)生異常的Controller中增加一個(gè)@ExceptionHandle注解的方法:
@GetMapping(value="/hello",produces={"text/html; charset=UTF-8"})
@ResponseBody
public String hello(ModelAndView model){
int c = 100 / 0;
return "<h1>User info</h1>";
}
@ExceptionHandler(Exception.class)
@ResponseBody
public String handle(Exception ex){
return "錯(cuò)了在helloworld Controller error msg is ===";
}運(yùn)行:

說明Hello方法中發(fā)生的異常,已經(jīng)被handle方法處理,前臺(tái)頁面不再會(huì)出現(xiàn)異常信息。
問題解決了!
但是@ExceptionHandle只在當(dāng)前Controller文件中生效,也就是說,當(dāng)前Controller中的方法、或者方法調(diào)用的service層、dao層等發(fā)生的異常,才會(huì)被捕獲到。其他Controller中發(fā)生的異常依然不會(huì)被捕獲。
這樣的話,就需要對(duì)每一個(gè)Controller增加@ExceptionHandle進(jìn)行處理,處理起來還是有點(diǎn)麻煩。
統(tǒng)一異常處理
@ExceptionHandle + @ControllerAdvice可以實(shí)現(xiàn)統(tǒng)一異常處理。
@ControllerAdvice注解可以實(shí)現(xiàn):
On startup, RequestMappingHandlerMapping and ExceptionHandlerExceptionResolver detect controller advice beans and apply them at runtime. Global @ExceptionHandler methods, from an @ControllerAdvice, are applied after local ones, from the @Controller. By contrast, global @ModelAttribute and @InitBinder methods are applied before local ones.
SpringMVC啟動(dòng)的過程中,RequestMappingHandlerMapping和ExceptionHandlerExceptionResolver會(huì)檢測(cè)到advice bean并且在運(yùn)行時(shí)會(huì)使用他們。在@ControllerAdvice中的@ExceptionHandler會(huì)變成一個(gè)全局的異常處理器、在本地異常處理器之后生效。并且,@ModelAttribute和 @InitBinder會(huì)在本地的之后生效。
這段話的意思就是,@ExceptionHandle + @ControllerAdvice之后,@ExceptionHandle就會(huì)變成全局異常處理器。所謂的本地異常處理器,就是寫在Controller中的@ExceptionHandle異常處理器。
這個(gè)工作是ExceptionHandlerExceptionResolver干的,源碼中可以看到:
@Nullable
protected ServletInvocableHandlerMethod getExceptionHandlerMethod(
@Nullable HandlerMethod handlerMethod, Exception exception) {
Class<?> handlerType = null;
//先找"local"異常處理器
if (handlerMethod != null) {
// Local exception handler methods on the controller class itself.
// To be invoked through the proxy, even in case of an interface-based proxy.
handlerType = handlerMethod.getBeanType();
ExceptionHandlerMethodResolver resolver = this.exceptionHandlerCache.get(handlerType);
if (resolver == null) {
resolver = new ExceptionHandlerMethodResolver(handlerType);
this.exceptionHandlerCache.put(handlerType, resolver);
}
Method method = resolver.resolveMethod(exception);
if (method != null) {
return new ServletInvocableHandlerMethod(handlerMethod.getBean(), method);
}
// For advice applicability check below (involving base packages, assignable types
// and annotation presence), use target class instead of interface-based proxy.
if (Proxy.isProxyClass(handlerType)) {
handlerType = AopUtils.getTargetClass(handlerMethod.getBean());
}
}
//再找advice的異常處理器
for (Map.Entry<ControllerAdviceBean, ExceptionHandlerMethodResolver> entry : this.exceptionHandlerAdviceCache.entrySet()) {
ControllerAdviceBean advice = entry.getKey();
if (advice.isApplicableToBeanType(handlerType)) {
ExceptionHandlerMethodResolver resolver = entry.getValue();
Method method = resolver.resolveMethod(exception);
if (method != null) {
return new ServletInvocableHandlerMethod(advice.resolveBean(), method);
}
}
}
return null;
}驗(yàn)證一下。
加一個(gè)MyGlobalExceptionController:
@ControllerAdvice
public class MyGlobalExceptionController {
@ExceptionHandler(Exception.class)
@ResponseBody
public String handle(Exception ex){
return return "錯(cuò)了MyGlobalExceptionController error msg is ===";
}
}先不去掉HelloWorldController中的異常處理器,運(yùn)行hello:

生效的是HelloWorldController中的異常處理器。
然后去掉HelloWorldController中的異常處理器:

寫在MyGlobalExceptionController中的全局異常處理器生效!
自定義異常處理器HandlerExceptionResolver
實(shí)現(xiàn)接口HandlerExceptionResolver,或者擴(kuò)展虛擬類AbstractHandlerMethodExceptionResolver(勉強(qiáng)可以考慮),定義自己的異常處理器。
其實(shí),非必要(沒想到有什么必要性)不建議!
以上就是SpringMVC使用@ExceptionHandler注解在Controller中處理異常的詳細(xì)內(nèi)容,更多關(guān)于SpringMVC異常處理的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- Spring中的@ExceptionHandler注解統(tǒng)一異常處理詳解
- Spring的異常處理@ExceptionHandler注解解析
- 關(guān)于SpringBoot使用@ExceptionHandler注解局部異常處理
- Spring中@ExceptionHandler注解的使用方式
- Spring中@ExceptionHandler注解的工作原理詳解
- Spring @ExceptionHandler注解統(tǒng)一異常處理和獲取方法名
- Spring中的@ControllerAdvice和@ExceptionHandler注解處理全局異常
- Spring中的@ExceptionHandler注解詳解與應(yīng)用示例
相關(guān)文章
spring如何集成cxf實(shí)現(xiàn)webservice接口功能詳解
這篇文章主要給大家介紹了關(guān)于spring如何集成cxf實(shí)現(xiàn)webservice接口功能的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家 的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起看看吧2018-07-07
Spring boot框架下的RabbitMQ消息中間件詳解
這篇文章詳細(xì)介紹了Spring Boot框架下的RabbitMQ消息中間件的基本概念、消息傳輸模型、環(huán)境準(zhǔn)備、Spring Boot集成以及消息生產(chǎn)和消費(fèi),感興趣的朋友跟隨小編一起看看吧2025-01-01
springBoot連接遠(yuǎn)程Redis連接失敗的問題解決
本文主要介紹了springBoot連接遠(yuǎn)程Redis連接失敗的問題解決,使用springboot里面的redisTemplate進(jìn)行連接的時(shí)候,卻發(fā)生了報(bào)錯(cuò),下面就來一起解決一下2024-05-05
HttpServletRequestWrapper干預(yù)Request處理流程解析
這篇文章主要分析在?Tomcat的處理?http?請(qǐng)求的流程中干預(yù)?Request對(duì)象,?通過基于HttpServletRequestWrapper和?Filter組合進(jìn)行干預(yù),有需要的朋友可以借鑒參考下,希望能夠有所幫助2023-09-09

