SpringMVC中怎么统一异常处理

发布时间:2021-06-17 14:12:50 作者:Leah
来源:亿速云 阅读:128

SpringMVC中怎么统一异常处理,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

一、需求

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

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 异常处理逻辑

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

推荐阅读:
  1. SpringBoot 统一异常处理
  2. SpringBoot 统一异常处理详解

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spring mvc

上一篇:PHP中如何通过设置系统环境变量来区分测试环境和正式环境

下一篇:VB6.0开发环境是怎么样的

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》