异常处理
SpringMVC: HandlerExceptionResolver接口
该接口的每个实现类都是异常的一种处理方式:
 
一、ExceptionHandlerExceptionResolver:主要提供@ExceptionHandler注解,并通过该注解处理异常。
//该方法捕获该类中抛出的ArithmeticException异常
@ExceptionHandler({ArithmeticException.class,ArrayIndexOutOfBoundsException.class})
public ModelAndView testArithmeticException(Exception e){
    System.out.println(e);
    ModelAndView mv=new ModelAndView("error");
    mv.addObject("e",e);
    return mv;
}

 

@ExceptionHandler标识的方法的参数必须是异常类型(Throwable或其子类),不能是其他类型的参数。
 
异常处理路径:最短优先。
如果有两个对应的异常处理方法:优先级是最短优先。
 
@ExceptionHandler只能捕获当前类中的异常
 
*如果想要捕获其他类中的异常:加@ControllerAdvice。
 
二、ResponseStatusExceptionResolver: 自定义异常显示@ResponseStatus
//自定义异常
@ResponseStatus(value = HttpStatus.FORBIDDEN,reason = "数组越界222")
public class MyArrayIndexOutofBoundsException extends Exception{
 
}
 
@RequestMapping("testMyException")
public String testMyException(@RequestParam("i") Integer i) throws MyArrayIndexOutofBoundsException {
    if(i==3){
        throw new MyArrayIndexOutofBoundsException();
    }
    return "success";
}

 

@ResponseStatus也可以加在方法前面。
@RequestMapping("testMyException2")
public String testMyException2(@RequestParam("i") Integer i){
    if(i==3){
        return "redirect:ResponseStatus";//不加前缀后缀
    }
    return "success";
}
 
@ResponseStatus(value = HttpStatus.FORBIDDEN,reason = "测试")
@RequestMapping("ResponseStatus")
public String testResponseStatus(){
    return "success";
}

 

三、异常处理的实现类:DefaultHandlerExceptionResolver,默认异常处理器
由此类提供。
SpringMVC在一些异常的基础上(300 500),新增了一些异常处理。
 
四、SimpleMappingExceptionResolver:通过配置实现异常处理