DEV Community

Discussion on: Avoiding Exceptions in ASP.NET Core

Collapse
 
altmank profile image
altmank

Could this be applied to async code? Was having some issues figuring out how.

Collapse
 
sam_ferree profile image
Sam Ferree

This is some older code, and I've played with a few versions of result now.

but I did often want to take a Result of Task of T and await it to get Result of T

Essentially to make anything awaitable you need to have a method that
returns a TaskAwaiter of T, or in our case Result of Task of T, which we can do with an extension method.

This is based off a different Result class I've been working with, but the basic idea should work.

        private static async Task<Result<TData>> FlipAsync<TData>(Result<Task<TData>> asyncResult)
        {
            try { return await asyncResult.Resolve(error => throw error); }
            catch (Exception error) { return error; }
        }

        public static TaskAwaiter<Result<TData>> GetAwaiter<TData>(this Result<Task<TData>> asyncResult) =>
            Result.FlipAsync(asyncResult).GetAwaiter();
Collapse
 
altmank profile image
altmank

Awesome, thank you for sharing. If you are willing, could you also add your newer approach to your Github? Would like to check that out too!