1. @ExceptionHandler
① 在 @ExceptionHandler 方法的入参中可以加入 Exception 类型的参数, 该参数即对应发生的异常对象
② @ExceptionHandler 方法的入参中不能传入 Map. 若希望把异常信息传导页面上,需要使用ModelAndView 作为返回值(若不想打印,那么还是使用String类型返回)
③ @ExceptionHandler 方法标记的异常有优先级的问题,即与这个异常最相关的优先。
④ @ControllerAdvice: 如果在当前 Handler 中找不到 @ExceptionHandler 方法来出来当前方法出现的异常, 则将去@ControllerAdvice 标记的类中查找 @ExceptionHandler 标记的方法来处理异常.
这是在当前的Handlers中(其中ArithmeticException为数学异常,当然也可以换成RuntimeException)
@ExceptionHandler({ArithmeticException.class})
public ModelAndView handleArithmeticException(Exception ex){
System.out.println("出异常了: " + ex);
ModelAndView mv = new ModelAndView("error");
mv.addObject("exception", ex);
return mv;
}
页面的打印error.jsp:${requestScope.exception }
这是单独写的一个类用来专门处理异常
@ControllerAdvice
public class SpringMVCTestExceptionHandler { //里面的方法还是一样的
2. ResponseStatusExceptionResolver
① 放在方法上:那么即使没有发生异常,也会显示那个定制的异常页面。
@ResponseStatus(reason="测试",value=HttpStatus.NOT_FOUND) //定制的异常页面显示
@RequestMapping("/testResponseStatusExceptionResolver")
public StringtestResponseStatusExceptionResolver(@RequestParam("i") int i){
② 放在类上:那么发生异常后就会出现定制的异常页面。
@ResponseStatus(value=HttpStatus.FORBIDDEN, reason="用户名和密码不匹配!")
public class UserNameNotMatchPasswordException extendsRuntimeException{
3. DefaultHandlerExceptionResolver
是对一些特殊异常的处理。(这个不用配置)
4. SimpleMappingExceptionResolver
如果希望对所有异常进行统一处理,可以使用SimpleMappingExceptionResolver,它将异常类名映射为视图名,即发生异常时使用对应的视图报告异常。
<!-- 配置使用 SimpleMappingExceptionResolver 来映射异常 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionAttribute" value="ex"></property>
//用来写异常的name,默认是exception ,在error.jsp中打印时所用的那个就是这个value
<property name="exceptionMappings">
<props> //用来说明是什么异常,要写全包含异常类名
<prop key="java.lang.ArrayIndexOutOfBoundsException">error</prop>
</props>
</property>
</bean>
@RequestMapping("/testSimpleMappingExceptionResolver")
public String testSimpleMappingExceptionResolver(@RequestParam("i") int i){
${requestScope.ex } //因为上面使用property将exception改为了ex
注:这时候不需要用像第一种处理方法中使用ModelAndView来将异常显示在页面上了,因为这种方法会自动的将异常存于request中,直接调用即可。