1. 程式人生 > >第四十三章:異常對映

第四十三章:異常對映

異常對映
異常機制是Java程式中針對有可能發生的問題所提前作出的應急解決方案。在SpringMVC中可以通過異常對映的方式,將異常型別和某個檢視名稱對應起來,讓使用者不是看到異常資訊,而是一個比較友好的介面。

侷限性:同步請求需要一個新的頁面時這樣操作是沒問題的,但是對於需要資料片段的非同步請求來說,就會導致Ajax請求收到的響應無法解析。
解決方案:

在spring-mvc.xml

<!-- 配置異常對映機制 -->
<!-- 為了能夠相容非同步請求的異常資訊響應格式,所以使用自定義CrowdfundingExceptionResolver類 -->
<bean id="simpleMappingExceptionResolver" class="com.crowdfunding.component.resolver.CrowdfundingExceptionResolver">
   <property name="exceptionMappings">
       <props>
           <prop key="java.lang.Exception">error</prop>
       </props>
   </property>
</bean>

重寫異常解析器的doResolveException()方法
為什麼要重寫?
在這裡插入圖片描述

重寫示例

public class CrowdfundingExceptionResolver extends SimpleMappingExceptionResolver {
    
    @Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception ex) {
        //判斷當前請求是否為非同步請求.如果 X-Requested-With 為 null,則為同步請求。X-Requested-With 為 XMLHttpRequest 則為 Ajax 請求。
        if ((request.getHeader("accept").contains("application/json") || (request.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").contains("XMLHttpRequest")))) {
            try {
                //建立ResultVO物件用來封裝Ajax響應結果
                ResultVO<String> resultVO = new ResultVO<>();
                resultVO.setResult(ResultVO.FAILED);
                resultVO.setData(ResultVO.NO_DATA);
                resultVO.setMessage(ex.getMessage());
                //將resultVO物件轉換為JSON資料
                Gson gson = new Gson();
                String json = gson.toJson(resultVO);
                //設定響應訊息頭
                response.setContentType("application/json;charset=UTF-8");
                //將resultVO的JSON資料返回給瀏覽器
                response.getWriter().write(json);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        //如果不滿足if條件說明是同步請求,則呼叫父類的方法按照常規方式處理
        return super.doResolveException(request, response, handler, ex);
    }
}

Gson的依賴
pom.xml

<dependency>
	<groupId>com.google.code.gson</groupId>
	<artifactId>gson</artifactId>
</dependency>