Closed asasine closed 4 years ago
As you say, the cache engine intentionally catches caching exceptions and passes them to the onCacheGetError
(etc) delegates for custom handling. You can do what you like in those handler delegates, though. To achieve your goal, you could simply code the onCacheGetError
and onCachePutError
delegates to throw exceptions which the wrapping retry policy handles. The delegates could just rethrow the exception passed as an input parameter, if desired.
onCacheGetError: (context, key, exception) =>
{
var logger = context["logger"] as ILogger;
logger?.LogWarning("Failed to get key {key}: {ex}", key, exception);
throw exception; // or using ExceptionDispatchInfo, if you prefer
}
Note also an alternative approach to this problem is to place the retry-for-cache-errors policy within a custom cache provider implementation, as discussed and exemplified here.
I think the PolicyGuardedAsyncCacheProvider<TResult>
implementation you suggest in your link is smart and provides a clean solution, one that is much more intentful than rethrowing exceptions in onCacheGetError
. I'll try that implementation for my use case, thanks!
Summary: What are you wanting to achieve? I'd like to wrap my calls to a cache policy in a retry policy such that any failed cache gets/puts will be retried per the policy. When using a distributed cache such as Redis, transient errors may occur such as timeouts or connection exceptions. These exceptions do not always indicate that the cache is unavailable and retries may often succeed. Wrapping the cache policy in a retry could help improve cache hits.
How can I achieve this using Polly's cache, retry, and wrap policies?
What code or approach do you have so far?
I've tried to wrap a cache policy with a retry policy that handles transient errors however this does not work. After reading through the documentation, it appears this may be by-design:
From https://github.com/App-vNext/Polly/wiki/Cache#throws
Using Microsoft.Extensions.DependencyInjection and other related packages, I'm registring policies into the policy registry:
Then I'm getting this policy and using it as such:
To test this, I stopped the local redis process that the distributed cache was connecting to then executed the
"myPolicy"
policy. This forces every connection attempt to throw aRedisConnectionException
which is logged in theonCacheGetError
andonCachePutError
delegates. I never see theonRetry
delegate log anything though.