当本机查询无法执行sqlgrammar异常和Exception之间执行的restcontrolleradvice类的方法时
@RestControllerAdvice
公共类ExceptionControllerAdvice {
@Autowired
Helper HelperUtilities;
@Autowired
HttpServletRequest request;
@Autowired
Telemetry tel;
@ExceptionHandler(SQLGrammarException.class)
public ResponseEntity<ErrorResponse> exceptionHandler(SQLGrammarException ex) {
ex.printStackTrace();
ErrorResponse error = new ErrorResponse();
error.setErrorCode(500);
error.setMessage(ex.getMessage());
// Log this error in Kibana using stdout
String CurrentUser = HelperUtilities.getCurrentUserNameFromJWT();
String ErrorDetails = "Server Side Error (UnHandled):: User - " + CurrentUser
+ " ::: Method - exceptionHandler(Exception ex) :: Error Details - "
+ HelperUtilities.getStackTraceAsString(ex);
return new ResponseEntity<ErrorResponse>(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> exceptionHandler(Exception ex) {
ex.printStackTrace();
ErrorResponse error = new ErrorResponse();
error.setErrorCode(400);
error.setMessage(ex.getLocalizedMessage());
String CurrentUser = HelperUtilities.getCurrentUserNameFromJWT();
String ErrorDetails = "Server Side Error (UnHandled):: User - " + CurrentUser
+ " ::: Method - exceptionHandler(Exception ex) :: Error Details - "
+ HelperUtilities.getStackTraceAsString(ex);
tel.setExeceptionEventData( HttpStatus.BAD_REQUEST.toString(),ErrorDetails, new Object() {
}.getClass().getEnclosingMethod().getName());
return new ResponseEntity<ErrorResponse>(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
最佳答案
Spring将以在SpringContext中注册的相同顺序调用ExceptionHandler。
使用@Order或@Priority批注以确保首先注册更具体的ExceptionHandler。
在你的情况下
@Order(1)
@ExceptionHandler(SQLGrammarException.class)
public ResponseEntity<ErrorResponse> exceptionHandler(SQLGrammarException ex)
{
....
}
@Order(2)
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> exceptionHandler(Exception ex) {
....
}
通过在Google中搜索“弹簧多个异常处理程序”在这里找到答案:Setting Precedence of Multiple @ControllerAdvice @ExceptionHandlers
所以这里的重点是:如果您有一个带有@ExceptionHandler for Exception的@ControllerAdvice,并且在另一个带有@ExceptionHandler的@ControllerAdvice类中注册了一个更具体的异常(如IOException),则第一个将被调用。如前所述,可以通过让@ControllerAdvice注释类实现Ordered或使用@Order或@Priority对其进行注释并为其指定适当的值,来控制该注册顺序。