文章目录
1、异常处理的思路2、实现步骤模拟错误(Controller类)1、编写异常类和错误页面2、自定义异常处理器3、在springmvc.xml中配置异常处理器
1、异常处理的思路
(1)系统中异常包括两类: 预期异常和运行时异常 RuntimeException,前者通过捕获异常从而获取异常信息, 后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。
(2)系统的 dao、service、controller 出现都通过 throws Exception 向上抛出,最后由 springmvc 前端 控制器交由异常处理器进行异常处理。
2、实现步骤
模拟错误(Controller类)
try {
int i
= 10/0;
} catch (Exception e
) {
e
.printStackTrace();
throw new SysException("查询所有用户出现的错误");
}
1、编写异常类和错误页面
(1)自定义异常类
public class SysException extends Exception{
private String message
;
@Override
public String
getMessage() { return message
;}
public void setMessage(String message
) {this.message
= message
; }
public SysException(String message
) {this.message
= message
; }
}
(2)编写异常error.jsp
<body>执行失败!${message }
</body>
2、自定义异常处理器
public class SysExceptionResolver implements HandlerExceptionResolver {
public ModelAndView
resolveException(HttpServletRequest httpServletRequest
,
HttpServletResponse httpServletResponse
, Object o
, Exception e
) {
SysException exception
= null
;
if(e
instanceof SysException){
exception
= (SysException
) e
;
}else{
exception
= new SysException("系统正在维护···");
}
ModelAndView mv
= new ModelAndView();
mv
.addObject("errorMsg",exception
.getMessage());
mv
.setViewName("error");
return mv
;
}
}
3、在springmvc.xml中配置异常处理器
<bean id="sysExceptionResolver" class="cn.itcast.exception.SysExceptionResolver"></bean>