SpringMVC9——異常處理

異常處理
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:通過配置實現異常處理