RestControllerAdvice
@RestControllerAdvice Spring Framework is a new feature in 4.3, which is a combination of notes @ControllerAdvice + @ResponseBody. So @RestControllerAdvice can help us to use RestfulApi handle exceptions by a cross-point @ExceptionHandler.
General Exceptions Exception
@RestControllerAdvice
public class MyExceptionTranslator {
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.OK)
public String handleNotFoundException(CustomNotFoundException ex) {
return ex.getMessage();
}
}
复制代码
Custom exception handling
Custom exception class
public class CustomNotFoundException extends RuntimeException{
public CustomNotFoundException(String msg) {
super(msg);
}
}
复制代码
Exception handling framework
@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;
}
}
复制代码
Reproduced in: https: //juejin.im/post/5d0b5ed8f265da1b80204c42