第一步:自定義異常類(繼承java中的Exception類)
/**
* 自定義異常
*/
public class SysException extends Exception{
/**
* 異常提示
*/
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public SysException(String message) {
this.message = message;
}
}
第二步:新建異常處理類(實(shí)現(xiàn)SpringMvc中的HandlerExceptionResolver接口)
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 異常處理
*/
public class ExceptionResover implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
SysException ex = null;
if (e instanceof SysException) {
ex = (SysException) e;
} else {
ex = new SysException("系統(tǒng)正在維護(hù)升級撞叨,詳情請聯(lián)系管理員");
}
// 跳轉(zhuǎn)異常頁面
ModelAndView mv = new ModelAndView();
mv.addObject("message", ex.getMessage());
mv.setViewName("excption");
return mv;
}
}
第三步:在Spring的配置文件中注冊異常處理類
<!-- 配置異常處理 -->
<bean id="sysException" class="work.chenc.exception.ExceptionResover"></bean>
第四步:新增異常時需要跳轉(zhuǎn)的頁面
第五步:手動模擬異常進(jìn)行測試(新增一個類)
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import work.chenc.exception.SysException;
@Controller
public class TestExceptController {
@RequestMapping(value = "/testException")
public String testException() throws SysException {
System.out.println("testException----------");
try {
int a = 10/0;
} catch (Exception e) {
e.printStackTrace();
throw new SysException("未知錯誤");
}
return "success";
}
}
總結(jié):在實(shí)際開發(fā)中無論是持久層(Da0)還是業(yè)務(wù)層(service)出現(xiàn)異常時我們都是將異常進(jìn)行拋出,然后在控制層我們對異常捕獲。在SpringMVC中我們可以一直將異常拋出,直至拋給SpringMVC的前端控制器(DispatcherServlet)在這里進(jìn)行異常處理,因?yàn)镈ispatcherServlet相當(dāng)于一個調(diào)度中心牍颈,瀏覽器所有的及服務(wù)端的數(shù)據(jù)返回都是要經(jīng)過DispatcherServlet