SpringMVC---异常处理ExceptionHandler注解

一:异常处理

  1. springMVC通过HandlerExceptionResolver处理程序的异常,包括handler映射,数据绑定及目标方法执行时的异常

 

二:ExceptionHandlerExceptionResolver 

  1. 主要处理handler中用@ExceptionHandler注解定义的方法
  2. @ExceptionHandler注解定义的方法优先级问题:例如发 生的是NullPointerException,但是声明的异常有 RuntimeException 和 Exception,此候会根据异常的最近 继承关系找到继承深度最浅的那个 @ExceptionHandler 注解方法,即标记了 RuntimeException 的方法
  3. ExceptionHandlerMethodResolver 内部若找不 到@ExceptionHandler 注解的话,会找 @ControllerAdvice 中的@ExceptionHandler 注解方法

三:实现

1.在handler方法添加@ExceptionHandler注解的方法

/*
	 * 1.在@ExceptionHandler方法的入参中可以加入Exception类型的参数,该参数即对应发生的异常对象
	 * 2.在@ExceptionHandler方法的入参中不能传入Map,若希望把信息传到页面上,则需要使用ModelAndView作为返回值
	 * 3.在@ExceptionHandler方法标记的异常有优先级的问题,会找与他匹配最近的异常
	 * 4.
	 */
	@ExceptionHandler(value= {ArithmeticException.class})
	public ModelAndView handlerArithmeticException(Exception ex) {
		System.out.println("出错了: "+ex);
		ModelAndView mv=new ModelAndView("error");
		mv.addObject("exception", ex);
		return mv;
	}
	
	@RequestMapping("testExceptionHandlerResolver")
	public String testExceptionHandlerResolver(@RequestParam("i") int i) {
		System.out.println("result:="+(10/i));
		return "success";
	}

2.测试页面

<a href="testExceptionHandlerResolver?i=10">test ExceptionHandlerResolver?i=10</a>
		  	<br>
<h3>error page</h3>
	${exception}

四:也可以定义一个全局的异常处理,在内部方法中没有找到@ExceptionHandler注解的方法,会找 @ControllerAdvice 中的@ExceptionHandler 注解方法

@ControllerAdvice
public class SpringMvcHandlerException {

	@ExceptionHandler(value= {ArithmeticException.class})
	public ModelAndView handlerArithmeticException(Exception ex) {
		System.out.println("出错了》》》》: "+ex);
		ModelAndView mv=new ModelAndView("error");
		mv.addObject("exception", ex);
		return mv;
	}
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值