springMVC的自带异常处理器: HandlerExceptionResolver
1.首先自定义异常:
public class CustomException extends Exception{ private String msg; public CustomException(String msg){ this.msg = msg; } public void setMsg(String msg){ this.msg = msg; } public String getMsg(){ return msg; } }2.自定义异常处理器(实现HandlerExceptionResolver)
public class CustomExceptionResolver implements HandlerExceptionResolver{ @Override public ModelAndView resolverException(HttpServletRequest request, HttpServletResponse response, Exception exception){ // 判断抛出的异常是否是自定义异常 CustomException customException; if(exception instanceof CustomException){ // 是 customException = (CustomException) exception; }else{ // 系统异常 customException = new CustomException("未知错误!"); } ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("error"); modelAndView.addObject("error",customException.getMsg()); return modelAndView; } }3.加载自定义的异常处理器 — springMVC.xml
<!-- 加载自定义异常处理器 --> <bean class="online.bendou.exception.CustomExceptionResolver" />4.添加error页面 在error.jsp中取出错误信息: ${error}
5.处理代码中可能出错的地方
public User queryUser(Integer id) throws CustomException{ User user = userMapper.findById(id); if(user != null){ return user; }else{ throw new CustomException("用户不存在!"); } }异常抛到最后, 将被异常处理器处理.