zoukankan      html  css  js  c++  java
  • SpringMVC——异常处理

    • Spring MVC 通过 HandlerExceptionResolver 处理程序的异常,包括 Handler 映射、数据绑定以及目标方法执行时发生的异常。
    • SpringMVC 提供的 HandlerExceptionResolver 的实现类

    <mvc:annotation-driven/>在容器中注册org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver

    ExceptionHandlerExceptionResolver

    • 主要处理 Handler 中用 @ExceptionHandler 注解定义的方法。
    package com.nchu.mybatis.controller;
    /**
     * Created by yangshijing on 2017/12/26 0026.
     */
    //@SessionAttributes(value={"user"}, types={String.class})
    @RequestMapping("/test")
    @Controller
    public class SpringMVCTest {
        private static final String SUCCESS = "success";
        @RequestMapping("/testHandlerExceptionResolver")
        public  String testHandlerExceptionResolver(@RequestParam("i") int i){
            int a = 10/i;
            return SUCCESS;
        }
        /**
         * 测试SpringMVC对异常的处理
         * 1. 在 @ExceptionHandler 方法的入参中可以加入 Exception 类型的参数, 该参数即对应发生的异常对象
         * 2. @ExceptionHandler 方法的入参中不能传入 Map. 若希望把异常信息传导页面上, 
       * 需要使用 ModelAndView 作为返回值
    * 3. @ExceptionHandler 方法标记的异常有优先级的问题. * 4. @ControllerAdvice: 如果在当前 Handler 中找不到 @ExceptionHandler
       * 方法来处理当前方法出现的异常,
    则将去 @ControllerAdvice 标记的类中查找
       * @ExceptionHandler 标记的方法来处理异常.
    */ @ExceptionHandler({RuntimeException.class}) public ModelAndView testException(Exception ex){ ModelAndView modelAndView = new ModelAndView("error"); modelAndView.addObject("exception", ex); return modelAndView; } }
    • @ExceptionHandler 注解定义的方法优先级问题:例如发生的是NullPointerException,但是声明的异常有RuntimeException 和 Exception,此候会根据异常的最近继承关系找到继承深度最浅的那个 @ExceptionHandler注解方法,即标记了 RuntimeException 的方法
    • ExceptionHandlerMethodResolver 内部若找不到@ExceptionHandler 注解的话,会找@ControllerAdvice 中的@ExceptionHandler 注解方法
    package com.nchu.mybatis.controller;
    
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.servlet.ModelAndView;
    
    /**
     * Created by yangshijing on 2018/1/7 0007.
    * 自定义异常处理类,会对全局声明的异常进行处理
    */ @ControllerAdvice public class NchuException { @ExceptionHandler({ArithmeticException.class}) public ModelAndView testException(Exception ex){ ModelAndView modelAndView = new ModelAndView("error"); modelAndView.addObject("exception", ex); System.out.print("12344"); return modelAndView; } }
  • 相关阅读:
    airprobe 安装 part2
    USRP Daugherboard: DBSRX
    电赛又见电赛!2011电赛之我见
    USRP Experiment 1: Data transmission
    How to Switch Between GDM and KDM on Ubuntu
    USRP Daugherboard: BasicRX
    Oracle Analyze 命令 详解
    Oracle SQL优化 总结
    Oracle SQL优化 总结
    Oracle 用拼接字符串更新表 测试
  • 原文地址:https://www.cnblogs.com/realshijing/p/8229079.html
Copyright © 2011-2022 走看看