zoukankan      html  css  js  c++  java
  • 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 正常测试即可

     

     

  • 相关阅读:
    PAT 1123 Is It a Complete AVL Tree
    PAT 1122 Hamiltonian Cycle
    PAT 1121 Damn Single
    PAT 1120 Friend Numbers
    JS数组的sort排序
    [转] jquery操作select(取值,设置选中)
    [转]2013和2014年中国互联网企业100强排行榜
    css 更换浏览器 默认图标
    [转]CSS禁止文字选择
    github 在线 创建文件夹
  • 原文地址:https://www.cnblogs.com/sjzxs/p/9502891.html
Copyright © 2011-2022 走看看