Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ToErrorOrAsync extension method #122

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

davidferneding
Copy link

In my current project, we are using a ToErrorOrAsync extension method to create ErrorOr-objects from async calls. We mainly use this to add conditions to database calls, allowing us to concisely check the returned value and define errors for non-matching return values.

Example:

public async Task<ErrorOr<User>> GetAdminUser(Guid userId)
{
    return await userRepository.FindById(id)
        .ToErrorOrAsync()
        .FailIf(x => x is null, UserErrors.NotFound(id))
        .Then(x => x!)
        .FailIf(x => !x.IsAdmin, UserErrors.InsufficientPermissions(id))
        .FailIf(x => x.IsDeactivated, UserErrors.Deactivated(id));
}

This can be solved by awaiting the call first, either by storing it in a variable (User? user = await userRepository.FindById(id); return user.ToErrorOr()...) or wrapping the call in brackets (return (await ...).ToErrorOr()...), but - at least for us - this extension method is preferred. The method works well with the existing Task<ErrorOr<T>>-overloads that have recently been added for the other methods (FailIf, Then, ...).

If you think this might be a good addition for this library, I'd be happy to get this merged and add changes if necessary.

This improves readability when using ErrorOr for async calls.
E.g.
```
User? user = await userRepository.FindById(id);
ErrorOr<User> userResult = user.ToErrorOr()
    .FailIf(x => x is null, UserErrors.NotFoundById(id))
    .Then(x => x!);
```
becomes
```
ErrorOr<User> user = await userRepository.FindById(id)
    .ToErrorOrAsync()
    .FailIf(x => x is null, UserErrors.NotFoundById(id))
    .Then(x => x!);
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant