1.异常处理思路
系统中的异常包括两类:预期异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码的开发、测试等手段减少运行时异常的发生。
系统的dao、service、controller出现异常都通过throws Exception向上抛出,最后由springmvc的前端控制器交由异常处理器进行处理(一个系统只有一个异常处理器)。
处理过程如下图所示:
2.全局异常开发处理
全局异常处理器处理思路: 解析出异常类型,如果该异常类型是系统自定义的异常,直接取出异常信息,在错误页面展示。如果该异常类型不是系统自定义的异常,构造一个自定义的异常类型(信息为“未知错误”)。
springmvc提供了一个HandlerExceptionResolver接口。
//全局异常处理器
public class CommonExceptionReslover implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object object, Exception exception) {
//handler就是处理器适配器要执行的Handler对象
String errorMessage = "";
//判断异常的类型
if (exception instanceof CustomerException) {
errorMessage = ((CustomerException)exception).getMessage();
} else {
errorMessage = "未知错误,请和管理员联系";
}
//跳转到错误消息页面
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("message", errorMessage);
modelAndView.setViewName("failed");
return modelAndView;
}
}
<%--错误页面显示异常信息--%>
<p>${message}</p>
3.自定义异常
对不同的异常类型定义异常类,继承Exception,需要时抛出此类异常。
//针对预期异常,需要在程序中抛出此类异常
public class CustomerException extends Exception{
//异常消息
private String message;
public CustomerException(String message) {
super(message);
this.message = message;
}
public String getMessage() {
return message;
}
}
4.配置异常处理器
<!-- 配置全局异常处理器 -->
<bean class="com.steven.ssm.utils.exception.CommonExceptionReslover"/>
5.异常测试(抛出)
在controller、service、dao中任意一处需要手动抛出异常。
如果是程序中手动抛出的异常,在错误页面中显示自定义的异常信息,如果不是手动抛出异常说明是一个运行时异常,在错误页面只显示“未知错误”。
//在商品修改的controller方法中抛出异常
@RequestMapping("/selectItem")
public ModelAndView selectItem(@RequestParam(value="id")Integer item_id) throws Exception{
Items item = itemsService.getItemById(item_id);
if(item == null){
throw new CustomerException("要查询的商品信息不存在!");
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("item",item);
modelAndView.setViewName("items/selectItem");
return modelAndView;
}
@Override
public Items getItemById(Integer itemId) throws Exception {
Items item = itemsMapperCustom.getItemById(itemId);
if(item == null){
throw new CustomerException("要查询的商品信息不存在!");
}
return item;
}