Spring?MVC的三種異常處理方式實例詳解
Spring MVC異常的處理流程
異常分為編譯時異常和運行時異常,編譯時異常我們 try-catch進行捕獲,捕獲后自行處理,而運行時異常是不 可預(yù)期的,就需要規(guī)范編碼來避免,在SpringMVC 中,不管是編譯異常還是運行時異常,都可以最終由 SpringMVC提供的異常處理器進行統(tǒng)一處理,這樣就避免了隨時隨地捕獲處理的繁瑣性。
SpringMVC 處理異常的思路是,一路向上拋,都拋給前端控制器 DispatcherServlet ,DispatcherServlet 在調(diào)用異常處理器ExceptionResolver進行處理,如下圖:
Spring MVC異常的處理方式
SpringMVC 提供了以下三種處理異常的方式:
- 簡單異常處理器:使用SpringMVC 內(nèi)置的異常處理器處理SimpleMappingExceptionResolver;
- 自定義異常處理器:實現(xiàn)HandlerExceptionResolver接口,自定義異常進行處理;
- 注解方式:使用@ControllerAdvice + @ExceptionHandler 來處理
簡單異常處理器SimpleMappingExceptionResolver
配置開啟SimpleMappingExceptionResolver, 并指定異常捕獲后的處理動作,當(dāng)發(fā)生了異常后,會被 SimpleMappingExceptionResolver 處理,跳轉(zhuǎn)到我們 配置的錯誤頁面error.html給用戶進行友好展示 。
<!--配置簡單異常處理器--> <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <!-- 異常捕獲后動作:展示視圖 --> <property name="defaultErrorView" value="/error.html"/> </bean
可以在配置SimpleMappingExceptionResolver時,指定一些參數(shù),例如:異常的類型
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="defaultErrorView" value="/error.html"/> <property name="exceptionMappings"> <props> <!-- 配置異常類型對應(yīng)的展示視圖 --> <prop key="java.lang.RuntimeException">/error.html</prop> <prop key="java.io.FileNotFoundException">/io.html</prop> </props> </property> </bean>
注解方式配置簡單映射異常處理器
@Bean public SimpleMappingExceptionResolver simpleMappingExceptionResolver(){ //創(chuàng)建SimpleMappingExceptionResolver SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver(); //設(shè)置默認(rèn)錯誤展示視圖 resolver.setDefaultErrorView("/error.html"); //定義Properties設(shè)置特殊異常對應(yīng)的映射視圖 Properties properties = new Properties(); properties.setProperty("java.lang.RuntimeException","/error.html"); properties.setProperty("java.io.FileNotFoundException","/io.html"); resolver.setExceptionMappings(properties); return resolver; }
自定義異常處理器
實現(xiàn)HandlerExceptionResolver接口自定義異常處理器,可以完成異常邏輯的處理。
public class MyHandlerExceptionResolver implements HandlerExceptionResolver { @Override //參數(shù)Object是當(dāng)前目標(biāo)方法處理器對象HandlerMethod public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("/error.html"); return modelAndView; } }
交給Spring管理異常處理器:
<bean class="com.fly.exception.MyHandlerExceptionResolver"></bean>
自定義異常處理器,返回Json格式字符串信息
@Component public class MyHandlerExceptionResolver implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { //編寫要返回的json格式的字符串 String jsonStr = "{\"code\":0,\"message\":\"error\",\"data\":\"\"}"; try { httpServletResponse.getWriter().write(jsonStr); } catch (IOException e1) { e1.printStackTrace(); } return null; } }
@ControllerAdvice + @ExceptionHandler 配置異常
@ControllerAdvice 注解本質(zhì)是一個 @Component,也會被掃描到,與此同時,具備AOP功能,默認(rèn)情況下對所有的Controller都進行攔截操作, 攔截后干什么呢?就需要再結(jié)合@ExceptionHandler、@InitBinder、@ModelAttribute 注解一起使用了,此 處我們講解的是異常,所以是@ControllerAdvice + @ExceptionHandler的組合形式編寫全局異常處理器類,使用@ControllerAdvice標(biāo)注,且@ExceptionHandler指定異常類型。
@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(RuntimeException.class) public ModelAndView runtimeHandleException(RuntimeException e){ System.out.println("全局異常處理器執(zhí)行...."+e); ModelAndView modelAndView = new ModelAndView("/error.html"); return modelAndView; } @ExceptionHandler(IOException.class) @ResponseBody public ResultInfo ioHandleException(IOException e){ //模擬一個ResultInfo ResultInfo resultInfo = new ResultInfo(0,"IOException",null); return resultInfo; } }
如果全局異常處理器響應(yīng)的數(shù)據(jù)都是Json格式的字符串的話,可以使用@RestControllerAdvice替代 @ControllerAdvice 和 @ResponseBody
@RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(RuntimeException.class) public ResultInfo runtimeHandleException(RuntimeException e){ //模擬一個ResultInfo ResultInfo resultInfo = new ResultInfo(0,"RuntimeException",null); return resultInfo; } @ExceptionHandler(IOException.class) public ResultInfo ioHandleException(IOException e){ //模擬一個ResultInfo ResultInfo resultInfo = new ResultInfo(0,"IOException",null); return resultInfo; } }
到此這篇關(guān)于Spring MVC的三種異常處理方式的文章就介紹到這了,更多相關(guān)Spring MVC異常處理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Springboot如何去掉URL后面的jsessionid
這篇文章主要介紹了Springboot如何去掉URL后面的jsessionid,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11spring啟動后保證創(chuàng)建的對象不被垃圾回收器回收
最近看到一個問題是,spring在啟動后如何保證創(chuàng)建的對象不被垃圾回收器回收?。所以本文結(jié)合jvm的垃圾回收機制和spring中的源代碼做出自己的一點猜測。有需要的朋友們可以參考借鑒。2016-09-09Spring Security獲取用戶認(rèn)證信息的實現(xiàn)流程
Spring Security是一個能夠為基于Spring的企業(yè)應(yīng)用系統(tǒng)提供聲明式的安全訪問控制解決方案的安全框架。它提供了一組可以在Spring應(yīng)用上下文中配置的Bean,充分利用了Spring IoC,DI和AOP功能,為應(yīng)用系統(tǒng)提供聲明式的安全訪問控制功能2022-12-12Spring Boot FeignClient 如何捕獲業(yè)務(wù)異常信息
這篇文章主要介紹了Spring Boot FeignClient 如何捕獲業(yè)務(wù)異常信息的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06使用Zxing實現(xiàn)二維碼生成器內(nèi)嵌圖片
二維碼在現(xiàn)實中的應(yīng)用已經(jīng)很廣泛了,本文介紹了使用Zxing實現(xiàn)二維碼生成器內(nèi)嵌圖片,有需要的可以了解一下。2016-10-10