• SpringMVC异常处理


    springMVC异常处理

    springmvc在处理请求过程中出现异常信息交由异常处理器进行处理,自定义异常处理器可以实现一个系统的异常处理逻辑。

    系统中异常包括两类:预期异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。

    简单案例:

    1.1 自定义异常类

     

      

    public class CustomException extends Exception {

     

    /** serialVersionUID*/

     

    private static final long serialVersionUID = -5212079010855161498L;

     

    public CustomException(String message){

     

    super(message);

     

    this.message = message;

     

    }

     

    //异常信息

     

    private String message;

     

    public String getMessage() {

     

    return message;

     

    }

     

     

    public void setMessage(String message) {

     

    this.message = message;

     

    }

     

    }

     

    1.2 自定义异常处理器

        

    public class CustomExceptionResolver implements HandlerExceptionResolver {

     

     

    @Override

     

    public ModelAndView resolveException(HttpServletRequest request,

     

    HttpServletResponse response, Object handler, Exception ex) {

     

    ex.printStackTrace();

     

    CustomException customException = null;

     

    //如果抛出的是系统自定义异常则直接转换

     

    if(ex instanceof CustomException){

     

    customException = (CustomException)ex;

     

    }else{

     

    //如果抛出的不是系统自定义异常则重新构造一个系统错误异常。

     

    customException = new CustomException("系统错误,请与系统管理 员联系!");

     

    }

     

    ModelAndView modelAndView = new ModelAndView();

     

    modelAndView.addObject("message", customException.getMessage());

     

    modelAndView.setViewName("error");

     

    return modelAndView;

     

    }

     

    }

     

    1.3 异常处理器配置(springmvc.xml中添加

     

     

    <!-- 异常处理器 -->

     

    <bean id="handlerExceptionResolver" class="cn.itcast.ssm.controller.exceptionResolver.CustomExceptionResolver"/>

    1.4 正常测试即可

     

     

  • 相关阅读:
    Window.ActiveXObject的用法 以及如何判断浏览器的类型
    PDO预处理
    *p=&a是把a的值赋给p,p=&a是把a的地址赋给p。
    牛客网
    关于stable_sort()和sort()的区别
    求最小公倍数
    成绩排序
    二叉树的存储、创建以及遍历
    关于sort函数的几种用法
    vector的用法
  • 原文地址:https://www.cnblogs.com/sjzxs/p/9502891.html
Copyright © 2020-2023  润新知