【SpringMVC】统一异常处理

一、需求

  • 一般项目中都需要作异常处理,基于系统架构的设计考虑,使用统一的异常处理方法。
  • 系统中异常类型有哪些?
  • 包括预期可能发生的异常、运行时异常(RuntimeException),运行时异常不是预期会发生的。
  • 针对预期可能发生的异常,在代码手动处理异常可以try/catch捕获,可以向上抛出。
  • 针对运行时异常,只能通过规范代码质量、在系统测试时详细测试等排除运行时异常。

二、统一异常处理解决方案

2.1 定义异常

  • 针对预期可能发生的异常,定义很多异常类型,这些异常类型通常继承于Exception。
  • 这里定义一个系统自定义异常类:
  • CustomException,用于测试。
public class CustomException extends Exception {
    
    //异常信息
    private String message;
    
    public CustomException(String message){
        super(message);
        this.message = message;
        
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
    

}

2.2 异常处理

  • 要在一个统一异常处理的类中要处理系统抛出的所有异常,根据异常类型来处理。

  • 统一异常处理的类是什么?

  • 前端控制器DispatcherServlet在进行HandlerMapping、调用HandlerAdapter执行Handler过程中,如果遇到异常,进行异常处理。

  • 在系统中自定义统一的异常处理器,写系统自己的异常处理代码。

  • 统一异常处理器实现HandlerExceptionResolver接口。

public class CustomExceptionResolver implements HandlerExceptionResolver  {

    //前端控制器DispatcherServlet在进行HandlerMapping、调用HandlerAdapter执行Handler过程中,如果遇到异常就会执行此方法
    //handler最终要执行的Handler,它的真实身份是HandlerMethod
    //Exception 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异常,对这类重新构造成一个CustomException,异常信息为“未知错误”
            customException = new CustomException("未知错误");
        }
        
        //错误 信息
        message = customException.getMessage();
        
        request.setAttribute("message", message);

        
        try {
            //转向到错误 页面
            request.getRequestDispatcher("/WEB-INF/jsp/error.jsp").forward(request, response);
        } catch (ServletException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return new ModelAndView();
    }

}

2.3 配置统一异常处理器

<!-- 定义统一异常处理器 -->
    <bean class="com.hao.ssm.exception.CustomExceptionResolver"></bean>

2.4 异常处理逻辑

  • 根据不同的异常类型进行异常处理。
  • 系统自定义的异常类是CustomException ,在controller方法中、service方法中手动抛出此类异常。
  • 针对系统自定义的CustomException异常,就可以直接从异常类中获取异常信息,将异常处理在错误页面展示。
  • 针对非CustomException异常,对这类重新构造成一个CustomException,异常信息为“未知错误”,此类错误需要在系统测试阶段去排除。
  • 在统一异常处理器CustomExceptionResolver中实现上边的逻辑。

猜你喜欢

转载自www.cnblogs.com/haoworld/p/springmvc-tong-yi-yi-chang-chu-li.html
今日推荐