springmvc异常处理器
生活随笔
收集整理的這篇文章主要介紹了
springmvc异常处理器
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
?
springmvc在處理請(qǐng)求過程中出現(xiàn)異常信息交由異常處理器進(jìn)行處理,自定義異常處理器可以實(shí)現(xiàn)一個(gè)系統(tǒng)的異常處理邏輯。
1 異常處理的思路
系統(tǒng)中異常包括兩類:預(yù)期異常和運(yùn)行時(shí)異常RuntimeException,前者通過捕獲異常從而獲取異常信息,后者主要通過規(guī)范代碼開發(fā)、通過測(cè)試手段減少運(yùn)行時(shí)異常的發(fā)生。
系統(tǒng)的dao、service、controller出現(xiàn)都通過throws Exception向上拋出,最后由springmvc前端控制器交由異常處理器進(jìn)行異常處理,如下圖:
2 自定義異常類
為了區(qū)別不同的異常,通常根據(jù)異常類型進(jìn)行區(qū)分,這里我們創(chuàng)建一個(gè)自定義系統(tǒng)異常。
如果controller、service、dao拋出此類異常說明是系統(tǒng)預(yù)期處理的異常信息。
package com.test.springmvc.exception;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;}}3 自定義異常處理器
public class CustomHandleException implements HandlerExceptionResolver {@Overridepublic ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,Exception exception) {// Object handler:指定是發(fā)生異常的地方,包名+類名+方法名(形參) 字符串 // 定義異常信息 String msg;// 判斷異常類型if (exception instanceof MyException) {// 如果是自定義異常,讀取異常信息msg = exception.getMessage();} else {// 如果是運(yùn)行時(shí)異常,則取錯(cuò)誤堆棧,從堆棧中獲取異常信息Writer out = new StringWriter();PrintWriter s = new PrintWriter(out);exception.printStackTrace(s);msg = out.toString();}// 把錯(cuò)誤信息發(fā)給相關(guān)人員,郵件,短信等方式// TODO// 返回錯(cuò)誤頁(yè)面,給用戶友好頁(yè)面顯示錯(cuò)誤信息ModelAndView modelAndView = new ModelAndView();modelAndView.addObject("msg", msg);modelAndView.setViewName("error");return modelAndView;} }4 異常處理器配置
在springmvc.xml中添加:
<!-- 配置全局異常處理器 --> <bean id="customHandleException" class="com.test.ssm.exception.CustomHandleException"/>5 準(zhǔn)備一個(gè)錯(cuò)誤頁(yè)面
<%@ 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>${msg}</h1> </body> </html>6 異常測(cè)試
/*** 查詢商品列表* * @return* @throws Exception*/ @RequestMapping(value = { "itemList", "itemListAll" }) public ModelAndView queryItemList() throws Exception {// 自定義異常if (true) {throw new MyException("自定義異常出現(xiàn)了~");}// 運(yùn)行時(shí)異常int a = 1 / 0;// 查詢商品數(shù)據(jù)List<Item> list = this.itemService.queryItemList();// 創(chuàng)建ModelAndView,設(shè)置邏輯視圖名ModelAndView mv = new ModelAndView("itemList");// 把商品數(shù)據(jù)放到模型中mv.addObject("itemList", list);return mv; }?
?
?
?
?
?
?
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/jepson6669/p/9038669.html
總結(jié)
以上是生活随笔為你收集整理的springmvc异常处理器的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 批量执行命令(SSH)
- 下一篇: 循环,函数,指针作业