码迷,mamicode.com
首页 > 编程语言 > 详细

SpringMVC——异常处理

时间:2018-01-07 21:53:01      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:nal   test   出现   string   spring   and   int   advice   执行   

  • 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; } }

SpringMVC——异常处理

标签:nal   test   出现   string   spring   and   int   advice   执行   

原文地址:https://www.cnblogs.com/realshijing/p/8229079.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!