SpringMVC通過使用 HandlerExceptionResolver處理程序異常。
在沒有加<mvc:annotation-driver />之前前普,SpringMVC的DispatcherServlet默認裝配AnnotationMethodHandlerExceptionResolver異常處理器肚邢。使用了<mvc:annotation-driver /> SpringMVC將裝配HandlerException異常處理器。
- SpringMVC異常處理器的使用
在Controller類的方法上加@ExceptionHandler({ArithmeticException.class})注解
@ExceptionHandler({ArithmeticException.class})
public String testExceptionHandler(Exception ex){
System.out.println("Exception : " + ex);
return "error";
}
- 將異常返回到頁面
注意,@ExceptionHandler注解的方法里不能用Map作為參數(shù)骡湖,如果需要需要將異常傳導到頁面上贱纠,需要使用ModelAndView作為返回值。
@ExceptionHandler({ArithmeticException.class})
public ModelAndView testExceptionHandler(Exception ex){
System.out.println("Exception : " + ex);
ModelAndView mv = new ModelAndView("error");
mv.addObject("exception", ex);
return mv;
}
- 異常處理器執(zhí)行的優(yōu)先關系
如果在一個Controller類里定義了兩個被@ExceptionHandler注解的方法响蕴,先被定義(代碼行數(shù)靠前)的將被執(zhí)行谆焊,后面的異常處理器被不被執(zhí)行。
@ExceptionHandler ({RuntimeException.class, NullPointException.class})
public String testExceptionHandler1(Exception ex) {
... some operate for exception ...
return "error";
}
@ExceptionHandler ({ArithmeticException.class})
public String testExceptionHandler2 (Exception ex){
... some operate for exception
return "error";
}
此時浦夷,當被@ExceptionHandler注解標識的方法所在的被@Controller注解標識類出現(xiàn)異常時辖试,將會調用異常處理器testExceptionHandler1方法劈狐,testExceptionHandler2將不會被調用罐孝。
- @ControllerAdvice 的使用
當被@Controller標識的類里沒有定義異常處理器時,當程序拋出異常時肥缔,將會調用被@ControllerAdvice標識類里被@ExceptionHandler標識的方法莲兢。
public class GeneralExceptionHandler {
@ExceptionHandler
public String generalExceptionHandler (Exception ex){
... some operation of ex ....
return "error";
}
}
@ResponseStatus注解
SpringMVC對異常的處理,不僅可以使用@ExceptionHandler续膳,而且可以使用@ResponseStatus注解改艇。作用范圍
@ResponseStatus不僅可以用在類上,也可以用在方法上坟岔。屬性
@ResponseStatus擁有兩個屬性
value:指定返回的狀態(tài)碼
reason:返回給頁面的信息實例
1.@ResponseStatus作用于類上
/**
* 自定義異常類:@ResponseStatus作用于類上
**/
@ResponseStatus (value = HttpStatus.FORBIDDEN, reason = "無訪問權限")
public class MyException extends RuntimeException {
}
@Controller
public class MyView {
@RequestMapping (value = "/testException")
private String testException(Exception ex) {
try {
int result = 1 / 0;
} catch (Exception e) {
throw new MyException();
}
return "error";
}
}
-
測試結果
測試結果
2.@ResponseStatus作用于方法上
@Controller
public class MyView {
@ResponseStatus (value = HttpStatus.NOT_FOUND, reason = "資源丟失啊啊啊")
@RequestMapping (value = "/testException")
private void testException(Exception ex) {
}
}
如果@ResponseStatus作用于方法上谒兄,無論方法執(zhí)行成功與否都會返回到自定義的異常頁面。
-
測試結果
測試結果