Вы можете использовать @RestControllerAdvice
. Создайте пользовательский класс исключений CustomRedisException
throw CustomRedisException
Исключение из каждого контроллера и обработайте его в отдельном class
с пометкой @RestControllerAdvice
.
@Override
public boolean delMyStatus(String key) {
try{
return redisTemplate.delete(key);
}
catch (Exception e){
if(e.getCause() != null && e.getCause().getCause() instanceof RedisException) { RedisException ex = (RedisException)e.getCause().getCause();
throw new CustomRedisException(ex);
} else {
throw new IllegalStateException("...");
}
}
return false;
}
Сделайте GlobalExceptionHandler как показано ниже.
@RestControllerAdvice(basePackages = "your base package here", basePackageClasses = RepositoryRestExceptionHandler.class)
public class GlobalRestExceptionHandler {
@ExceptionHandler
public ResponseEntity<ErrorResponse> handleCustomException(final CustomRedisExceptionex) {
// code for exception handling here.
return new ResponseEntity<>(
new ErrorResponse(HttpStatus.PRECONDITION_FAILED.value(), ex.getMessage()),
HttpStatus.PRECONDITION_FAILED);
}
}