Spring MVC框架:第十七章:異常映射
異常映射
異常機(jī)制是Java程序中針對(duì)有可能發(fā)生的問題所提前作出的應(yīng)急解決方案。在SpringMVC中可以通過異常映射的方式,將異常類型和某個(gè)視圖名稱對(duì)應(yīng)起來,讓用戶不是看到異常信息,而是一個(gè)比較友好的界面。
局限性:同步請(qǐng)求需要一個(gè)新的頁面時(shí)這樣操作是沒問題的,但是對(duì)于需要數(shù)據(jù)片段的異步請(qǐng)求來說,就會(huì)導(dǎo)致Ajax請(qǐng)求收到的響應(yīng)無法解析。
解決方案:
在spring-mvc.xml
<!-- 配置異常映射機(jī)制 -->
<!-- 為了能夠兼容異步請(qǐng)求的異常信息響應(yīng)格式,所以使用自定義CrowdfundingExceptionResolver類 -->
<bean id="simpleMappingExceptionResolver" class="com.crowdfunding.component.resolver.CrowdfundingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="java.lang.Exception">error</prop>
</props>
</property>
</bean>
分布式架構(gòu)中沒有Spring-mvc.xml那我們應(yīng)該怎么辦呢?
可以使用注解,例如:
@ControllerAdvice
public class MyExceptionResolver{
@ExceptionHandler(value=Exception.class)
public String resolveException(Exception e, Model model){
model.addAttribute("exception",e);
return "error";
}
}
重寫異常解析器的doResolveException()方法
為什么要重寫?
重寫示例
public class CrowdfundingExceptionResolver extends SimpleMappingExceptionResolver {
@Override
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) {
//判斷當(dāng)前請(qǐng)求是否為異步請(qǐng)求.如果 X-Requested-With 為 null,則為同步請(qǐng)求。X-Requested-With 為 XMLHttpRequest 則為 Ajax 請(qǐng)求。
if ((request.getHeader("accept").contains("application/json")
|| (request.getHeader("X-Requested-With") != null &&
request.getHeader("X-Requested-With").contains("XMLHttpRequest")))) {
try {
//創(chuàng)建ResultVO對(duì)象用來封裝Ajax響應(yīng)結(jié)果
ResultVO<String> resultVO = new ResultVO<>();
resultVO.setResult(ResultVO.FAILED);
resultVO.setData(ResultVO.NO_DATA);
resultVO.setMessage(ex.getMessage());
//將resultVO對(duì)象轉(zhuǎn)換為JSON數(shù)據(jù)
Gson gson = new Gson();
String json = gson.toJson(resultVO);
//設(shè)置響應(yīng)消息頭
response.setContentType("application/json;charset=UTF-8");
//將resultVO的JSON數(shù)據(jù)返回給瀏覽器
response.getWriter().write(json);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//如果不滿足if條件說明是同步請(qǐng)求,則調(diào)用父類的方法按照常規(guī)方式處理
return super.doResolveException(request, response, handler, ex);
}
}
Gson的依賴
pom.xml
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>