This tutorial will walk you through the steps to implement custom error handler and fail-safe caching in Spring applications

By default, SimpleCacheErrorHandler is used and simply throws the exception back to the client. However, in practice, failing to retrieve an object from the cache, due to connection issues or cache infrastructure goes down, should not affect to the main functioning. Spring provides CacheErrorHandler interface, a cache error handler strategy for you to handling those circumstances

Implement CacheErrorHandler interface

The CacheErrorHandler interface provides 4 methods including handleCacheGetError, handleCachePutError, handleCacheEvictError and handleCacheClearError to handle errors thrown by @Cachable, @CachePut, and @CacheEvict

The following give you a CacheErrorHandler implementation example


CustomCacheErrorHandler logs the error for further investigation instead of throwing back to client

Register the custom CacheErrorHandler

You can implement CachingConfigurer interface or extend from CachingConfigurerSupport class to register the custom CacheErrorHandler

The following give you an example with CachingConfigurerSupport

import org.springframework.cache.annotation.CachingConfigurerSupport;  
import org.springframework.cache.interceptor.CacheErrorHandler;  
import org.springframework.context.annotation.Configuration;

@Configuration
public class CachingConfiguration extends CachingConfigurerSupport {  
    @Override
    public CacheErrorHandler errorHandler() {
        return new CustomCacheErrorHandler();
    }
}


Testing

Try to stop your Redis test server while running the application and compare the different between the default and custom error handler for Spring Cache


Conclusion

In this tutorial, we walk though the steps to implement fail-safe caching in Spring applications. You can find the full source code at https://github.com/hellokoding/hellokoding-courses/tree/master/springboot-examples/springboot-caching-redis