標籤:
exception-mapping 元素: 配置當前 action 的聲明式異常處理
exception-mapping 元素中有 2 個屬性
exception: 指定需要捕獲的的異常類型。異常的全類名
result: 指定一個響應結果, 該結果將在捕獲到指定異常時被執行, 既可以來自當前 action 的聲明, 也可以來自 global-results 聲明.
可以通過 global-exception-mappings 元素為應用程式提供一個全域性的異常捕獲映射. 但在 global-exception-mappings 元素下聲明的任何 exception-mapping 元素只能引用在 global-results 元素下聲明的某個 result 元素
聲明式異常處理機制由 ExceptionMappingInterceptor 攔截器負責處理, 當某個 exception-mapping 元素宣告的異常被捕獲到時, ExceptionMappingInterceptor 攔截器就會向 ValueStack 中添加兩個對象:
exception: 表示被捕獲異常的 Exception 對象
exceptionStack: 包含著被捕獲異常的棧
可以在視圖上通過 <s:property> 標籤顯示異常訊息 I:在設定檔中配置全域異常(針對特定action的) <action name=
"user_*" class =
"actions.UserAction" method=
"{1}" > <exception-mapping result=
"input" exception=
"java.lang.Exception" > </exception-mapping> <result name=
"login_success" type=
"redirect" >/success.jsp </result> <result name=
"input">/index.jsp </result> </action> 當程式發生沒有被抓取異常時,ExceptionMappingInterceptor 首先去設定檔查看有沒有配置全域異常資訊如果有就會把異常資訊放入棧中,否則就會報出 500錯誤: II:可以通過 global-exception-mappings 元素為應用程式提供一個全域性的異常捕獲映射<!-- 全域異常結果類型 --> <global-results> <result name=
"input">/index.jsp </result> </global-results> <!-- 全域異常捕獲 --> <global-exception-mappings> <exception-mapping result=
"input" exception=
"java.lang.Exception" > </exception-mapping> </global-exception-mappings> ExceptionMappingInterceptor 攔截器源碼解析:
public
class ExceptionMappingInterceptor
extends AbstractInterceptor { @Override
public String intercept(ActionInvocation invocation)
throws Exception { String result;
try { result = invocation.invoke(); }
catch (Exception e) {
if (isLogEnabled()) { handleLogging(e); } //擷取設定檔中的異常配置資訊 List<ExceptionMappingConfig> exceptionMappings = invocation.getProxy().getConfig().getExceptionMappings(); String mappedResult =
this.findResultFromExceptions(exceptionMappings, e);
if (mappedResult !=
null) { result = mappedResult; //把異常資訊壓入值棧中 publishException(invocation,
new ExceptionHolder(e)); }
else {
throw e; } }
return result; } //壓入到值棧中
protected
void publishException(ActionInvocation invocation, ExceptionHolder exceptionHolder) { invocation.getStack().push(exceptionHolder); }}
異常處理: exception-mapping 元素