springmvc自定義異常處理器


6b450c3c818f46f2be772ec024d3e4f8

當dispatchServlet接收到controller拋出的異常時,會將異常交由 HandlerExceptionResolver

異常處理器處理!我們可以創建自定義異常處理器實現該接口來處理自定義異常

 

1) 自定義異常類

public class MyException extends Exception {
    // 異常信息
    private String message;
 
    public MyException() {
       super();
    }
 
    public MyException(String message) {
       super();
       this.message = message;
    }
 
    public String getMessage() {
       return message;
    }
 
    public void setMessage(String message) {
       this.message = message;
    }
 
}

 

2)自定義異常處理器

public class CustomHandleException implements HandlerExceptionResolver {
 
    @Override
   public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
           Exception exception) {
       // 定義異常信息
       String msg;
 
       // 判斷異常類型
       if (exception instanceof MyException) {
           // 如果是自定義異常,讀取異常信息
           msg = exception.getMessage();
       } else {
           // 如果是運行時異常,則取錯誤堆棧,從堆棧中獲取異常信息
           Writer out = new StringWriter();
           PrintWriter s = new PrintWriter(out);
           exception.printStackTrace(s);
           msg = out.toString();
 
       }
 
       // 把錯誤信息發給相關人員,郵件,短信等方式
       // TODO
 
       // 返回錯誤頁面,給用戶友好頁面顯示錯誤信息
       ModelAndView modelAndView = new ModelAndView();
       modelAndView.addObject("msg", msg);
       modelAndView.setViewName("error");
 
       return modelAndView;
    }
}

 

3)在springmvc.xml中配置異常處理器

<!-- 配置全局異常處理器 -->
<bean
id="customHandleException" class="cn.itcast.ssm.exception.CustomHandleException"/>

 

4)定制錯誤頁面

<%@ 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>

 

5)測試異常處理

@RequestMapping(value = "/item/itemlist.action")
public ModelAndView itemList() throws MyException{
        
        List<Items> list = itemService.selectItemsList();
        
        if(true){
            throw new MyException("商品列表不能為空!!");
        }
        
        ModelAndView mav = new ModelAndView();
        mav.addObject("itemList", list);
        mav.setViewName("itemList");
        return mav;
    }

 

9a4c08a5bf624c50bce967b981607779


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM