Search code examples
c#language-ext

How can I extract the Exception from a faulted Result?


Please see code below, I am using the LanguageExt.Common.Result class:

public async Task<Result<bool>> DoSomething()
{
    try
    {
        await Something();
        return new Result<bool>(true);
    }
    catch (MyException ex)
    {
        return new Result<bool>(ex);
    }
}

And this

public async Task<Result<MyClass>> DoNext()
{
    var result = await DoSomething();

    if (result.IsFaulted)
    {
        return new Result<MyClass>(GET_EXCEPTION_FROM_result); // <<==== HERE ===
    }

    var data = new MyClass();
    return new Result<MyClass>(data);
}

How can I extract the exception from the faulted result ?

I know I can use result.Match<Result<MyClass>>(SuccessLambda, failureLambda) but the lambdas can not be async.

################# ADDED ###############

The first version of DoNext looked like this:

public async Task<Result<MyClass>> DoNext()
{
    var result = await DoSomething();

    return result.Match<Result<MyClass>>(
        async canDo => {
            var myClass = await GetAsync(...);
            return new Result<Myclass>(myclass);
        },
        ex => new Result<MyClass>(ex);
    )
}

But the lambdas can not be async.


Solution

  • I think I finally got the right way to do that, you should stay functional:

    public async Task<Result<MyClass>> DoNext()
    {
        var result = await DoSomething();
    
        return await result.MapAsync<MyClass>(async canDo =>
        {
            var myClass = await GetAsync(...);
            return myclass;
        });
    }
    

    You map the success path to another object. Any error state coming from the first Result object will be transferred to the next one.