第一步:自定義類實現異常處理類的接口
public class CustomExceptionResolver implements HandlerExceptionResolver{
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object obj,
Exception e) {
// obj:包名+類名+方法名(形參) 字符串, 將這些字符串信息記錄在日誌文件中,方便以後查看,可以使用log4j記錄日誌文件
ModelAndView mav = new ModelAndView();
//判斷異常爲類型
if(e instanceof MessageException){
//預期異常
MessageException me = (MessageException)e;
mav.addObject("error", me.getMsg());
}else{
mav.addObject("error", "未知異常");
}
mav.setViewName("error");
return mav;
}
}
第二步:在springmvc配置文件實例化這個異常處理類
<!-- Springmvc的異常處理器 -->
<bean class="com.itheima.springmvc.exception.CustomExceptionResolver"/>
第三步:寫一個美觀的異常顯示頁面error.jsp