springmvc在處理請求過程中出現異常信息交由異常處理器進行處理,自定義異常處理器可以實現一個系統的異常處理邏輯。
異常處理思路
系統中異常包括兩類:預期異常和運行時異常RuntimeException,前者通過捕獲異常從而獲取異常信息,后者主要通過規范代碼開發、測試通過手段減少運行時異常的發生。
系統的dao、service、controller出現都通過throws Exception向上拋出,最后由springmvc前端控制器交由異常處理器進行異常處理,如下圖:
2016-12-05_215246.png
自定義異常類
為了區別不同的異常通常根據異常類型自定義異常類,這里我們創建一個自定義系統異常,如果controller、service、dao拋出此類異常說明是系統預期處理的異常信息。
public class CustomException extends Exception {
/** serialVersionUID*/
private static final long serialVersionUID = -5212079010855161498L;
public CustomException(String message){
super(message);
this.message = message;
}
//異常信息
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}```
自定義異常處理器
public class CustomExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
ex.printStackTrace();
CustomException customException = null;
//如果拋出的是系統自定義異常則直接轉換
if(ex instanceof CustomException){
customException = (CustomException)ex;
}else{
//如果拋出的不是系統自定義異常則重新構造一個未知錯誤異常。
customException = new CustomException("未知錯誤,請與系統管理 員聯系!");
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("message", customException.getMessage());
modelAndView.setViewName("error");
return modelAndView;
}
}```
錯誤頁面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>錯誤頁面</title>
</head>
<body>
您的操作出現錯誤如下:<br/>
${message }
</body>
</html>
異常處理器配置
在springmvc.xml中添加:
<!-- 異常處理器 -->
<bean id="handlerExceptionResolver" class="cn.itcast.ssm.controller.exceptionResolver.CustomExceptionResolver"/>```
異常測試
修改商品信息,id輸入錯誤提示商品信息不存在。
修改controller方法“editItem”,調用service查詢商品信息,如果商品信息為空則拋出異常:
// 調用service查詢商品信息
Items item = itemService.findItemById(id);
if(item == null){
throw new CustomException("商品信息不存在!");
}```
在service中拋出異常方法同上。