@RestControllerAdvice是Spring Framework 4.3的一個新特性,它是一個結合了@ControllerAdvice + @ResponseBody的註解。因此@RestControllerAdvice能夠幫助咱們經過一個橫切點@ExceptionHandler來使用RestfulApi處理異常。bash
@RestControllerAdvice
public class MyExceptionTranslator {
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.OK)
public String handleNotFoundException(CustomNotFoundException ex) {
return ex.getMessage();
}
}
複製代碼
自定義異常類框架
public class CustomNotFoundException extends RuntimeException{
public CustomNotFoundException(String msg) {
super(msg);
}
}
複製代碼
異常處理框架ui
@RestControllerAdvice
public class MyExceptionTranslator {
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.OK)
public String handleNotFoundException(CustomNotFoundException ex) {
return ex.getMessage();
}
//自定義的異常處理
@ExceptionHandler(CustomNotFoundException.class)
@ResponseStatus(HttpStatus.OK)
public ResponseMsg handleNotFoundException(CustomNotFoundException ex) {
ResponseMsg responseMsg = new ResponseMsg(ex.getMessage());
return responseMsg;
}
}
複製代碼