异常处理
为了给用户一个良好的体验,可以将数据持久层和业务逻辑层的异常抛给控制器,让浏览器显示一个友好的界面。
流程模拟
1.用户执行操作时,.数据持久层和业务逻辑层出现异常
<a href="user/testException">异常</a>
2.控制器捕获异常。
@RequestMapping(path = "/testException")
public String testException() throws SysException{
System.out.println("testException执行了。。。");
try {
int i = 10/0;
} catch (Exception e) {
e.printStackTrace();
throw new SysException("错误了baby");
}
return "success";
}
3.控制器将异常给处理器,处理器要实现HandlerExceptionResolver 接口,
public class SysExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
SysException ex = null;
//e表示捕获的异常
if(e instanceof SysException){
ex = (SysException) e;
}else{
ex = new SysException("系统维护中。。。");
}
//处理器对象
ModelAndView mv = new ModelAndView();
//将控制器捕获的异常接受,并保存在一个key为errorMsg值为ex.getMessage()的键值对中。
mv.addObject("errorMsg",ex.getMessage());
//捕获的异常应该跳转到那个页面
mv.setViewName("error");
return mv;
}
}
4.注入异常处理器
<bean id="sysExceptionResolver" class="com.springmvc.exception.SysExceptionResolver">