系统中异常包括两类:预期异常和运行时异常RuntimeException,
前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。
系统的dao、service、controller出现都通过throws Exception向上抛出,
最后由springmvc前端控制器交由异常处理器进行异常处理
一 实现HandlerExceptionResolver接口的方式
自定义异常类:
/**
* 自定义异常类
*/
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;
}
}
Error页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>Title</title> </head> <body> ${errorMsg} </body> </html>
自定义异常处理器
/** * 异常处理器 */ public class SysExceptionResolver implements HandlerExceptionResolver{ /** * 处理异常业务逻辑 * @param request * @param response * @param handler * @param ex * @return */ public resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { SysException sysException = null;
if(ex instanceof SysException){
//如果抛出的是系统自定义异常则直接转换 sysException = (SysException)ex; }else{
//如果抛出的不是系统自定义异常, 则重新构造一个系统错误异常 sysException= new SysException("系统正在维护...."); } // 创建ModelAndView对象 ModelAndView mv = new ModelAndView(); mv.addObject("errorMsg",sysException.getMessage()); mv.setViewName("error"); return mv; } }
配置异常处理器 或者使用 @Component 标签,让 Spring 管理
<!--配置异常处理器--> <bean id="sysExceptionResolver" class="cn.itcast.exception.SysExceptionResolver"/>
控制器测试代码:
@Controller @RequestMapping("/user") public class UserController { @RequestMapping("/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"; } }
二 使用SimpleMappingExceptionResolver
Spring 也提供默认的实现类 SimpleMappingExceptionResolver,
需要使用时只需要使用注入到 Spring 配置文件进行声明即可。
自定义实现类与默认的实现类,可同时使用。
<!-- 自定义的实现类 --> <bean id="exceptionHandler" class="com.enh.test.CustomExceptionHandler"/>
<!-- 默认的实现类注入 --> <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!-- 为所有的异常定义默认的异常处理页面,exceptionMappings未定义的异常使用本默认配置 --> <property name="defaultErrorView" value="error"></property>
<!----> <property name="exceptionAttribute" value="ex"></property>
<!--
定义需要特殊处理的异常,用类名或完全路径名作为key,异常页文件名作为值, 将不同的异常映射到不同的页面上。 --> <property name="exceptionMappings"> <props> <prop key="IOException">error/ioexp</prop> <prop key="java.sql.SQLException">error/sqlexp</prop> </props> </property> </bean>