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;
	}
}
发布了64 篇原创文章 · 获赞 12 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_39093474/article/details/103897166