使用 @restcontrolleradvice 配合 @exceptionhandler 可以统一捕获缓存操作异常。核心做法是定义一个全局异常处理器类,在其中编写处理特定缓存异常(如 redisconnectionexception 或 cacheputfailureexception)的方法,并返回统一的错误响应结构。这样当缓存服务不可用或写入失败时,应用不会直接抛出原始异常堆栈,而是拦截并转换为前端友好的 json 格式。

如何配置全局异常处理器以拦截 Redis 连接异常?
通过继承 ResponseEntityExceptionHandler 或直接使用 @RestControllerAdvice 注解的类,可以捕获所有控制器层抛出的未处理异常。针对 Redis 连接中断,通常捕获 org.springframework.data.redis.RedisConnectionException。在处理方法中,记录日志并构建一个包含状态码和错误信息的 Result 对象返回。这确保了即使底层数据库连接池断开,API 依然能返回标准的 HTTP 500 或自定义错误码,而不是让 Tomcat 容器生成默认的 HTML 错误页。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@EnableCaching
public class CacheApplication {
public static void main(String[] args) {
SpringApplication.run(CacheApplication.class, args);
}
}
import org.springframework.data.redis.connection.RedisConnectionException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(RedisConnectionException.class)
@ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
public String handleRedisError(RedisConnectionException ex) {
return "Cache service unavailable: " + ex.getMessage();
}
}
预期结果:当 Redis 服务器关闭时,调用任何带 @Cacheable 的接口将返回 HTTP 503 及上述文本,而非 500 内部错误。
如何处理缓存写入失败导致的业务回滚?
在使用 @CachePut 或 @CacheEvict 时,如果缓存写入失败但业务逻辑已成功执行,默认行为可能导致数据不一致。可以通过捕获 org.springframework.cache.CacheOperationInvocationContext 相关的异常或在 Service 层手动包裹 try-catch 来处理。更推荐的做法是利用 Spring 的 CacheErrorHandler 接口实现自定义策略,或者在全局异常处理器中区分“只读”和“读写”操作的异常。对于写操作失败,可以选择忽略异常以保证主业务流程继续,同时记录警告日志,避免因为缓存组件故障导致整个交易流程中断。

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.stereotype.Component;
import org.springframework.lang.NonNull;
@Component
public class CustomCacheErrorHandler implements CacheErrorHandler {
@Override
public void handleCacheGetError(@NonNull RuntimeException exception,
@NonNull org.springframework.cache.Cache cache,
@NonNull Object key) {
System.err.println("Cache read failed for key: " + key);
}
@Override
public void handleCachePutError(@NonNull RuntimeException exception,
@NonNull org.springframework.cache.Cache cache,
@NonNull Object key, @NonNull Object value) {
System.err.println("Cache write failed for key: " + key);
}
@Override
public void handleCacheEvictError(@NonNull RuntimeException exception,
@NonNull org.springframework.cache.Cache cache,
@NonNull Object key) {
System.err.println("Cache eviction failed for key: " + key);
}
@Override
public void handleCacheClearError(@NonNull RuntimeException exception,
@NonNull org.springframework.cache.Cache cache) {
System.err.println("Cache clear failed");
}
}
预期结果:当 cache.put() 抛出异常时,控制台打印警告信息,但 Controller 正常返回成功状态,主业务数据已持久化到数据库。
基于程序中某个输入、条件或结果的具体问题
当输入参数为 null 且配置了 allowNullValues = false 时,Spring Cache 会抛出 IllegalArgumentException。在全局异常处理器中,如果不单独捕获此异常,它将被归类为通用 500 错误。实际上,这是客户端传入非法参数的表现,应返回 400 Bad Request。因此,需要在 GlobalExceptionHandler 中增加对 IllegalArgumentException 的特化处理,或者在 Service 层进行前置校验。若依赖全局捕获,需确保该异常优先于其他通用异常被匹配,或者明确指定其对应的 HTTP 状态码为 400,以符合 RESTful 规范。


















