要在一个统一异常处理的类中要处理系统抛出的所有异常,根据异常类型来处理。
统一异常处理的类是什么?
前端控制器DispatcherServlet在进行HandlerMapping、调用HandlerAdapter执行Handler过程中,如果遇到异常,都会调用这个统一异常处理类。当然该类只有实现HandlerExceptionResolver接口才能叫统一异常处理类。
1.定义统一异常处理器类
/**
* Created by codingBoy on 16/11/18.
* 自定义异常处理器
*/
public class CustomExceptionResolver implements HandlerExceptionResolver
{
//前端控制器DispatcherServlet在进行HandlerMapping、
// 调用HandlerAdapter执行Handler过程中,如果遇到异常就会执行此方法
//参数中的handler是最终要执行的Handler,它的真实身份是HandlerMethod
//ex就是接受到的异常信息
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response,
Object handler, Exception ex) {
//输出异常
ex.printStackTrace();
//统一异常处理代码
//针对系统自定义的CustomException异常,就可以直接从一场中获取一场信息,将异常处理在错误页面展示
//异常信息
String message=null;
CustomException customException=null;
//如果ex是系统自定义的异常,我们就直接取出异常信息
if (ex instanceof CustomException)
{
customException= (CustomException) ex;
}else {
customException=new CustomException("未知错误");
}
//错误信息
message=customException.getMessage();
request.setAttribute("message",message);
try {
//转向到错误页面
request.getRequestDispatcher("/WEB-INF/jsp/error.jsp").forward(request,response);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return new ModelAndView();
}
}
2.配置统一异常处理器
<!--定义统一异常处理器-->
<bean class="exception.CustomExceptionResolver"></bean>
3.测试抛出异常由统一异常处理器捕获
可以在controller方法、service方法、dao实现类中抛出异常,要求dao、service、controller遇到异常全部向上抛出异常,方法向 上抛出异常throws Exception。
在ItemsServiceImpl.java的findItemsById方法中添加如下内容:
@Override
public ItemsCustom findItemsById(int id) throws Exception {
Items items=itemsMapper.selectByPrimaryKey(id);
//如果查询的商品信息为空,抛出系统自定义的异常
if (items==null)
{
throw new CustomException("修改商品信息不存在");
}
//在这里以后随着需求的变化,需要查询商品的其它相关信息,返回到controller
//所以这个时候用到扩展类更好,如下
ItemsCustom itemsCustom=new ItemsCustom();
//将items的属性拷贝到itemsCustom
BeanUtils.copyProperties(items,itemsCustom);
return itemsCustom;
}