异常处理
异常处理思路: 系统中异常包括两类:预期异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,或者主要通过规范代码开发、测试通过手段减少运行时异常的发生。 系统的dao、service、controller出现都通过throws Exception向上抛出,最后有springmvc前端控制器交由异常处理器进行异常处理。 一般自定义异常属于预期异常而并非运行时异常springmvc提供全局异常处理器(一个系统只有一个异常处理器)进行统一异常处理。自定义异常类 对不同的异常类型定义异常类,继承Exception。 public class CustomException extends Exception{ //异常信息 public String message; public CustomException(String message){ super(message); this.message = message; } pubilc void setMessage(String message) { this.message = message; } public String getMessage() { return message; } }全局异常处理器 思路: 系统遇到异常,在程序中手动抛出,dao抛给service,service抛给controller,controller抛给前端控制器,前端控制器调用全局异常处理器。 全局异常处理器思路: 解析出异常类型 如果该异常类型是系统自定义的异常,直接取出异常信息,在错误页面展示 如果该异常类型不是系统自定义的异常,构造一个自定义的异常类型(信息为“未知错误”) springmvc提供了一个全局异常处理器接口HandlerExceptionResolver public class CustomExceptionResolver implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HtttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { //handler就是处理器适配器要执行的Handler对象(只有method) //解析出异常类型 //如果该异常类型是系统自定义的异常,直接取出异常信息,在错误页面展示 //如果该异常类型不是系统自定义的异常,构造一个自定义的异常类型(信息为“未知错误 ”) CustomException customException = null; if(ex instanceof CustomException){ customException = (CustomException)ex; }else{ customException=new CustomException("未知错误"); } String message=customException.getMessage(); ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("message",message); modelAndView.setViewName("error); return modelAndView; } }错误页面 <title><错误提示/title> </head> <body> ${message} </boy>在springmvc.xml配置全局异常处理器 <!-- 全局异常处理器,只要实现HandlerExceptionResolver接口就是全局异常处理器 --> <bean class="cn.itcast.ssm.exception.CustomExceptionResolver"></bean>异常测试: 在controller、service、dao中任意一处需要手动抛出异常 如果是程序手动抛出的异常,需要在错误页面显示自定义的异常信息,如果不是我们手动抛出的异常说明是一个运行期异常,在错误页面显示“未知异常” 与业务功能相关的异常,建议在service中抛出; 与业务功能没有关系的异常,建议在controller中抛出。