SpringMVC異常處理器程式碼示例
阿新 • • 發佈:2018-12-18
SpringMVC異常處理器
一.定義異常處理類設定規則 MyExceptionHandler.java
package com.igeek.ssm.exections; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; /** * @author www.igeehome.com * * TODO 統一的異常處理器 * * 2018年10月27日下午2:19:31 */ public class MyExceptionHandler implements HandlerExceptionResolver { Logger logger = Logger.getLogger(MyExceptionHandler.class); @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { //判斷異常是什麼異常? if(ex instanceof NullPointerException){ logger.error("空指標異常"); logger.error(ex.getMessage()); //記錄異常(記錄到檔案,資料庫) //發郵件 //發簡訊 //提醒維護人員 }else if(ex instanceof ClassCastException){ logger.error("型別轉換異常"); logger.error(ex.getMessage()); }else if(ex instanceof NumberFormatException){ logger.error("數字格式轉換異常"); logger.error(ex.getMessage()); } //必須響應異常結果處理頁面 ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("error"); modelAndView.addObject("msg", "系統異常:"+ex.getMessage()); return modelAndView; } }
二.在springMVC.xml中配置bean
<!-- 配置異常處理器 -->
<bean class="com.igeek.ssm.exections.MyExceptionHandler"/>
三.定義錯誤頁面 error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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>Insert title here</title> </head> <body> <h1>系統發生異常了!</h1> <br /> <h1>異常資訊</h1> <br /> <h2>${msg }</h2> </body> </html>