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 正常测试即可

     

     

  • 相关阅读:
    gcc链接g++编译生成的静态库和动态库的makefile示例
    gcc将多个静态库链接成一个静态库
    linux c redirect 重定向
    iOS开发如何提高
    致PHP路上的“年轻人”
    显示系统时间--带有秒数
    在 Linux 中使用日志来排错
    程序员必备:技术面试准备手册
    你的Java代码对JIT编译友好么?
    悟空:用Go语言编写的全文搜索引擎
  • 原文地址:https://www.cnblogs.com/sjzxs/p/9502891.html
Copyright © 2011-2022 走看看