異常處理過程

我們可以直接在Controller 裏創建 帶有 @ExceptionHandler 註解的異常處理方法。

@ExceptionHandler({ArithmeticException.class})
	public String exception(Exception e) {//出現java.lang.ArithmeticException異常時交由該方法處理
		System.out.println(e.getMessage());
		return "error";
	}

也可以單獨創建一個java類加上 @ControllerAdvice 對所有Controller 類裏的同樣異常進行處理。

@ControllerAdvice
public class MathExceptionHandler {
	
	@ExceptionHandler(ArithmeticException.class)
	public String exception(Exception e) {
		System.out.println(e.getMessage());
		return "userinfo/error";
	}
}

同時也可以配置在 Spring文件中配置 SimpleMappingExceptionResolve 用於服務器端當發生異常時根據發生的異常類型跳轉到指定的視圖以顯示異常信息

<!-- 配置SimpleMappingExceptionResolver視圖解析器 -->
	<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
		<!-- 配置異常屬性名:exceptionAttribute默認值爲exception,此時jsp頁面通過${exception}顯示異常信息;添加<property name="exceptionAttribute" value="ex"></property>配置後,則通過${ex}顯示異常信息 -->
		<property name="exceptionAttribute" value="ex"></property>
		<property name="exceptionMappings">
			 <props>
			 	<!-- 服務器端異常均指向error.jsp頁面 -->
		        <prop key="java.lang.Throwable">error</prop> 
		     </props> 
		</property>
	</bean>

 

在SpringMVC一個請求執行過程中,一旦爆發了一個異常就會在 doDispatch 中被捕獲,放入 dispatchException 中然後傳給 processDispatchResult 方法處理。

 

在進入processDispatchResult ,判斷exception 不爲空,向下執行 processHandlerException

 

 

對每一個解析器調用異常解析函數,返回一個視圖,此函數結束之後返回至 render 方法。render參考今天的同一篇博文。

 

進入 resolveException 執行異常解析。

 在上述的接口中我們可以看出 使用SimpleMappingException 的接口

 

 

爬。有點亂。先碼着,回來再改。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章