SpringMVC 异常处理
HandlerExceptionResolver接口及其实现类
HandlerExceptionResolver接口为SpringMVC处理异常的顶级接口,该接口的每个实现类都是异常的一种处理方式。
1.ExceptionHandlerExceptionResolver实现类提供的@ExceptionHandler注解
2.ResponseStatusExceptionResolver实现类提供的@ResponseStatus注解
3.DefaultHandlerExceptionResolver实现类为SpringMVC在一些常见异常的基础上(300,500,404),新增了一些异常,这里就不详细讲述了。
4.SimpleMappingExceptionResolver实现类是通过配置实现异常的处理。
1.ExceptionHandlerExceptionResolver类
ExceptionHandlerExceptionResolver类提供了@ExceptionHandler注解,,可以通过该注解处理异常。
注意:@ExceptionHandler注解所标识的方法参数必须是异常类型,不能包含其他类型的参数。
异常处理路径:最短优先。
@ExceptionHandler注解默认只能捕获当前类中的异常方法。
如果发生异常的方法和处理异常的方法不在一个类中,则需要加:
@ControllerAdvice注解,此注解一般用于标注类,代表当前类只处理异常。
@ExceptionHandler注解示例:
//该方法可以捕获本类中需要抛出的ArithmeticException异常
@ExceptionHandler({ArithmeticException.class})
public String handlerArithmeticException(ArithmeticException e) {
System.out.println(e);
return "error";
}
@ControllerAdvice注解示例:
@ControllerAdvice
public class MyExceptionHandler {
@ExceptionHandler({Exception.class})
public ModelAndView handlerArithmeticException(Exception e) {
ModelAndView mv=new ModelAndView("error");
mv.addObject("e", e);
System.out.println(e);
return mv;
}
}
总结:
如果一个方法用于处理异常,并且只处理当前类中的异常,用@ExceptionHandler注解即可;
如果一个方法用于处理异常,并且只处理当所有类中的异常,则需要在类前加@ControllerAdvice注解在处理异常的方法前加@ExceptionHandler注解
2.ResponseStatusExceptionResolver类
ResponseStatusExceptionResolver类提供了@ResponseStatus注解,通过该注解可以实现自定义异常显示页面。
@ResponseStatus注解可以标注在类前和方法前
@ResponseStatus注解标注在类前示例:
//以后如果如果出现MyArrayIndexOutOfBoundsException异常,则会在页面显示@ResponseStatus定义的信息
@ResponseStatus(value = HttpStatus.FORBIDDEN,reason = "数组越界")
//自定义数组越界异常
public class MyArrayIndexOutOfBoundsException extends Exception{
}
处理前台请求示例:
@RequestMapping("testMyException")
public String testMyException(@RequestParam("i") Integer i) throws MyArrayIndexOutOfBoundsException {
//当接收到i的值为3时抛出MyArrayIndexOutOfBoundsException异常
if(i==3) {
throw new MyArrayIndexOutOfBoundsException();
}else {
return "sucess";
}
}
@ResponseStatus注解标注在方法前示例:
//请求处理方法
@RequestMapping("testMyException2")
public String testMyException2(@RequestParam("i") Integer i) {
if(i==3) {
return "redirect:testMyException3";
}else {
return "sucess";
}
}
//异常处理方法
@ResponseStatus(value = HttpStatus.FORBIDDEN,reason = "数组越界")
@RequestMapping("testMyException3")
public String testMyException3() {
return "";
}
3.SimpleMappingExceptionResolver类通过配置实现异常的处理
如果发生异常,异常对象变量会被保存在exceptionAttribute的value中,并且会放入request域中,如果不写的话异常变量的默认值是exception
<!-- SimpleMappingExceptionResolver:以配置方式处理异常 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!-- 如果发生异常,异常对象变量会被保存在exceptionAttribute的value中,并且会放入request域中,
如果不写的话异常变量的默认值是exception
-->
<property name="exceptionAttribute" value="e"></property>
<property name="exceptionMappings" >
<props>
<!-- 相当于catch(ArithmeticException e){跳转 error 页面} -->
<prop key="java.lang.ArithmeticException">
error
</prop>
<prop key="java.lang.NullPointerException">
error
</prop>
</props>
</property>
</bean>