error-or
error-or copied to clipboard
Add ToErrorOrAsync extension method
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.