- 在全局異常處理類(lèi)上標(biāo)記
@ControllerAdvice
確保該處理類(lèi)能被掃描到并裝載進(jìn)spring容器
@ControllerAdvice
public class GlobalExceptionHandler {
}
- 在相應(yīng)的處理異常方法上添加
@ExceptionHandler
(被處理的Exception.class)晋南,該方法會(huì)處理被處理的Exception及其子類(lèi)
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseBody
String handleException(){
return "Exception Deal!";
}
}
或者這樣寫(xiě),參數(shù)中添加異常參數(shù)
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler()
@ResponseBody
String handleException(Exception e){
return "Exception Deal! " + e.getMessage();
}
}