一、 异常处理思路
系统中异常包括:编译时异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。在开发中,不管是dao层、service层还是controller层,都有可能抛出异常,在springmvc中,能将所有类型的异常处理从各处理过程解耦出来,既保证了相关处理过程的功能较单一,也实现了异常信息的统一处理和维护
二、异常处理
1.Controller层抛出异常
@RequestMapping(value = { "itemList", "itemListAll" })
public ModelAndView queryItemList() {
// 查询商品数据
List<Item> list = this.itemService.queryItemList();
if(list == null){
throw new CustomeException("查询信息不存在!");
}
// 运行时异常
int a = 1 / 0;
// 创建ModelAndView,设置逻辑视图名
ModelAndView mv = new ModelAndView("itemList");
// 把商品数据放到模型中
mv.addObject("itemList", list);
return mv;
}
2.自定义异常类 CustomException
//定义一个简单的异常类
public class CustomException extends Exception {
//异常信息
public String message;
public CustomException(String message) {
super(message);
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
3. 使用Spring MVC提供的简单异常处理器 SimpleMappingExceptionResolver
异常信息的统一处理和维护
public class CustomHandleException implements HandlerExceptionResolver{
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj,
Exception ex) {
// 发生异常地方 Service层 方法 包名+类名+方法名(形参) 的一个字符串
// 定义异常信息
String msg;
// 判断异常类型
if (exception instanceof MyException) {
// 如果是自定义异常,读取异常信息
msg = exception.getMessage();
} else {
// 如果是运行时异常,则取错误堆栈,从堆栈中获取异常信息
Writer out = new StringWriter();
PrintWriter s = new PrintWriter(out);
exception.printStackTrace(s);
msg = out.toString();
}
// 把错误信息发给相关人员,邮件,短信等方式
// TODO
// 返回错误页面,给用户友好页面显示错误信息
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("msg", msg);
modelAndView.setViewName("error");
return modelAndView;
}
}
4. 配置spring-mvc.xml文件加入异常处理器
<!-- 配置全局异常处理器 -->
<bean id="customHandleException" class="cn.mark.ssm.exception.CustomHandleException"/>