Skip to content

Commit

Permalink
feat: add ToErrorOrAsync extension method for Tasks
Browse files Browse the repository at this point in the history
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!);
```
  • Loading branch information
davidferneding committed Nov 14, 2024
1 parent ff7eac7 commit e713126
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/ErrorOr/ErrorOr.ToErrorOrExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,14 @@ public static ErrorOr<TValue> ToErrorOr<TValue>(this TValue value)
return value;
}

/// <summary>
/// Creates an <see cref="ErrorOr{TValue}"/> instance with the result of the given <see cref="Task{TValue}"/>.
/// </summary>
public static async Task<ErrorOr<TValue>> ToErrorOrAsync<TValue>(this Task<TValue> value)
{
return await value;
}

/// <summary>
/// Creates an <see cref="ErrorOr{TValue}"/> instance with the given <paramref name="error"/>.
/// </summary>
Expand Down
15 changes: 15 additions & 0 deletions tests/ErrorOr/ErrorOr.ToErrorOrTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,21 @@ public void ValueToErrorOr_WhenAccessingValue_ShouldReturnValue()
result.Value.Should().Be(value);
}

[Fact]
public async Task TaskToErrorOrAsync_WhenAccessingValue_ShouldReturnValue()
{
// Arrange
int value = 5;
Task<int> task = Task.FromResult(value);

// Act
ErrorOr<int> result = await task.ToErrorOrAsync();

// Assert
result.IsError.Should().BeFalse();
result.Value.Should().Be(value);
}

[Fact]
public void ErrorToErrorOr_WhenAccessingFirstError_ShouldReturnSameError()
{
Expand Down

0 comments on commit e713126

Please sign in to comment.