App-vNext/Polly · error · ArgumentNullException

Value cannot be null. (Parameter 'onCacheGet')

Error message

Value cannot be null. (Parameter 'onCacheGet')

What it means

Thrown at policy-construction time by the legacy Polly v7 base overload Policy.Cache(...) with full callbacks. onCacheGet is the action invoked when a value is successfully read from cache; even though it is an optional-feeling callback, this overload requires it to be non-null (it is invoked on every cache hit). Polly fails fast with ArgumentNullException.

Source

Thrown at src/Polly/Caching/CacheSyntax.cs:358

    {
        if (cacheProvider == null)
        {
            throw new ArgumentNullException(nameof(cacheProvider));
        }

        if (ttlStrategy == null)
        {
            throw new ArgumentNullException(nameof(ttlStrategy));
        }

        if (cacheKeyStrategy == null)
        {
            throw new ArgumentNullException(nameof(cacheKeyStrategy));
        }

        if (onCacheGet == null)
        {
            throw new ArgumentNullException(nameof(onCacheGet));
        }

        if (onCacheMiss == null)
        {
            throw new ArgumentNullException(nameof(onCacheMiss));
        }

        if (onCachePut == null)
        {
            throw new ArgumentNullException(nameof(onCachePut));
        }

        return new CachePolicy(cacheProvider, ttlStrategy, cacheKeyStrategy, onCacheGet, onCacheMiss, onCachePut, onCacheGetError, onCachePutError);
    }
}

View on GitHub (pinned to d0e46bdb1e)

Solutions

  1. Pass a non-null Action<Context,string> for onCacheGet (e.g. an empty lambda (_) => { }).
  2. If you do not need these callbacks, use a simpler overload that does not require them.
  3. Use the helper EmptyCallback from Polly if available, or define a static no-op action.

Example fix

// before
Policy.Cache(provider, ttlStrategy, keyFunc, null, onMiss, onPut, onGetErr, onPutErr);
// after
Policy.Cache(provider, ttlStrategy, keyFunc, (ctx, key) => { /* log hit */ }, onMiss, onPut, onGetErr, onPutErr);
Defensive patterns

Strategy: validation

Validate before calling

if (onCacheGet is null) throw new InvalidOperationException("onCacheGet is required by this overload (use a simpler overload or a no-op).");
var policy = Policy.Cache(cacheProvider, ttlStrategy, keyFunc, onCacheGet, onMiss, onPut, onGetErr, onPutErr);

Type guard

static bool IsCallbackValid(System.Action<Polly.Context,string>? a) => a is not null;

Prevention

When it happens

Trigger: Calling the full-callback Cache(...) overload with the onCacheGet argument set to null.

Common situations: You wired some lifecycle callbacks but left onCacheGet null; you assumed callbacks were optional in this detailed overload (they are not — only the *Error callbacks accept null); overload-resolution put you on this method.

Related errors


AI-assisted analysis of App-vNext/Polly@d0e46bdb1e (2026-08-13). Data as JSON: /api/errors/2127af135c41db95. Report an issue: GitHub.