How can I extract the Exception from a faulted Result?

266 Views Asked by At

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.

2

There are 2 best solutions below

0
acmoune On BEST ANSWER

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.

0
acmoune On

@AztecCodes, it seems like the API has changed. There is no overload of IfFail returning an exception, so I instead did this (Please let me know if I missed something):

if (result.IsSuccess)
{
    ...
}
else
{
    Exception exception = default!;
    result.IfFail(ex => exception = ex);
    return new Result<MyClass>(exception);
}