springmvc在處理請求過程中出現異常信息交由異常處理器進行處理,自定義異常處理器可以實現一個系統的異常 處理邏輯。
系統異常包括兩類: 預期異常 和運行異常RuntimeExecption,前者 通過捕獲異常從而獲取異常信息,后者 主要通過規范代碼開發、測試通過手段減少運行時異常的發生。
系統的dao、service、controller出現都通過throws exception 向上拋出,最后由springmvc前端控制器交由異常處理器進行異常處理
為了區別不同的異常通常根據異常類型自定義異常類,這里我們創建一個自定義系統異常,如果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.ty.controller.exceptionResolver.CustomExceptionResolver"/>
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。