ZiggyCreatures / FusionCache

FusionCache is an easy to use, fast and robust hybrid cache with advanced resiliency features.
MIT License
1.87k stars 96 forks source link

[FEATURE] 💣 FailSafe Without Exceptions #280

Closed jodydonetti closed 3 months ago

jodydonetti commented 3 months ago

Problem

Currently the way to activate fail-safe is for a factory to throw an exception.

This makes sense, since the whole point of fail-safe is to protect us when an error occurs while executing a factory. The issue is that there may be other ways to do it, for example by using a variation of the Result Pattern or similar approaches, in which throwing an exception is not necessary.

Community user @chrisbbe asked exactly for that: a way to tell the factory that it failed, without having to throw an exception.

Is there a way to do it?

Solution

The idea is to create a new method on the execution context of the factory (of type FusionCacheFactoryExecutionContext<TValue>) named Fail, with a signature like Fail(string errorMessage).

Example:

var productResult = await cache.GetOrSetAsync<Result<Product>>(
    $"product:{id}",
    async (ctx, ct) =>
    {
        var productResult = GetProductFromDb(id);

        if (productResult.IsSuccess == false)
        {
            return ctx.Fail(productResult.Error);
        }

        return productResult;
    },
    opt => opt.SetDuration(duration).SetFailSafe(true)
);

By calling it just like we already call Modified(...) or NotModified(...) it will be possible to trigger the fail-safe flow, all without having to throw an exception, saving on performance and making our code a little more functional in the meantime.

jodydonetti commented 3 months ago

Hi all, v1.3.0 is out 🥳