异常处理器分析
分析:
系统中异常包括两类:预期异常和运行时异常 RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。
系统的 dao、service、controller 出现都通过 throws Exception 向上抛出,最后由 springmvc 前端 控制器
交由异常处理器
进行异常处理,如下图:
异常处理思路
- Controller调用service,service调用dao,异常都是向上抛出的,最终有DispatcherServlet找异常处理器进行异常的处理。
SpringMVC的异常处理
- 自定义异常类
public class SysException extends Exception{
// 存储异常信息
private String message;
public SysException(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
- 自定义异常处理器
public class SysExceptionResolver implements HandlerExceptionResolver {
/**
* 处理异常的业务逻辑
*/
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
System.out.println("异常处理方法执行了...");
// 获取到异常对象
SysException exception =null;
if (e instanceof SysException){
exception = (SysException)e;
}else{
exception = new SysException("系统正在维护....");
}
// 创建ModelAndView对象
ModelAndView mv = new ModelAndView();
mv.addObject("errorMsg",exception.getMessage());
// 跳转页面
mv.setViewName("error");
return mv;
}
}
- 配置异常处理器
<!-- 配置异常处理器-->
<bean id="sysExceptionResolver" class="code.exception.SysExceptionResolver">
</bean>
- 页面和控制器方法
<a href="user/testException">异常处理...</a>
@Controller
@RequestMapping(path = "/user")
public class UserController {
@RequestMapping(path = "/testException")
public String testException() throws Exception{
System.out.println("testException 执行了。。。");
try {
// 模拟异常
int i=10/0;
} catch (Exception e) {
// 打印异常信息
e.printStackTrace();
// 抛出自定义异常信息
throw new SysException("运行出现错误了...");
}
return "success";
}
}
- 页面跳转结果