在我的Spring-boot Rest API项目中,我们将@RestControllerAdvice类配置为处理在应用程序的任何位置生成的所有异常。但是,当我们从Spring-jdbc模板queryForObject方法获得运行时异常时,它就无法捕获。
我的@RestControllerAdvice类捕获异常
@RestControllerAdvice
public class ExceptionHandlingController {
@ExceptionHandler(value = {EmptyResultDataAccessException.class})
public ResponseEntity<ErrorMessage> emptyResultDataAccessException(EmptyResultDataAccessException ex, WebRequest request) {
ErrorMessage errorMessage = new ErrorMessage(new Date(), ex.getMessage(),
request.getDescription(false));
return new ResponseEntity<>(errorMessage, new HttpHeaders(), HttpStatus.NO_CONTENT);
}
@ExceptionHandler(value = { Exception.class })
public ResponseEntity<ErrorMessage> handleAnyException(Exception ex, WebRequest request) {
ErrorMessage errorMessage = new ErrorMessage(new Date(), ex.getLocalizedMessage(),
request.getDescription(false));
return new ResponseEntity<>(errorMessage, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}