Skip to content

Commit

Permalink
feat: Value will now throw when errors are present
Browse files Browse the repository at this point in the history
The Value property is now properly encapsulated. When errors are present, the property getter will throw, similar to other properties like Errors or FirstError.

Signed-off-by: Kenny Pflug <kenny.pflug@live.de>
  • Loading branch information
feO2x committed May 9, 2024
1 parent 015ddd7 commit 1f43ff3
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 7 deletions.
13 changes: 12 additions & 1 deletion src/ErrorOr/ErrorOr.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,18 @@ private ErrorOr(TValue value)
/// <summary>
/// Gets the value.
/// </summary>
public TValue Value => _value!;
public TValue Value
{
get
{
if (IsError)
{
throw new InvalidOperationException("The Value property cannot be accessed when errors have been recorded. Check IsError before accessing Value.");
}

return _value;
}
}

/// <summary>
/// Gets the first error.
Expand Down
14 changes: 8 additions & 6 deletions tests/ErrorOr/ErrorOr.InstantiationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -144,17 +144,18 @@ public void CreateFromErrorList_WhenAccessingErrorsOrEmptyList_ShouldReturnError
}

[Fact]
public void CreateFromErrorList_WhenAccessingValue_ShouldReturnDefault()
public void CreateFromErrorList_WhenAccessingValue_ShouldThrowInvalidOperationException()
{
// Arrange
List<Error> errors = new() { Error.Validation("User.Name", "Name is too short") };
ErrorOr<Person> errorOrPerson = ErrorOr<Person>.From(errors);

// Act
Person value = errorOrPerson.Value;
var act = () => errorOrPerson.Value;

// Assert
value.Should().Be(default);
act.Should().Throw<InvalidOperationException>()
.And.Message.Should().Be("The Value property cannot be accessed when errors have been recorded. Check IsError before accessing Value.");
}

[Fact]
Expand Down Expand Up @@ -247,16 +248,17 @@ public void ImplicitCastSingleError_WhenAccessingErrors_ShouldReturnErrorList()
}

[Fact]
public void ImplicitCastError_WhenAccessingValue_ShouldReturnDefault()
public void ImplicitCastError_WhenAccessingValue_ShouldThrowInvalidOperationException()
{
// Arrange
ErrorOr<Person> errorOrPerson = Error.Validation("User.Name", "Name is too short");

// Act
Person value = errorOrPerson.Value;
var act = () => errorOrPerson.Value;

// Assert
value.Should().Be(default);
act.Should().Throw<InvalidOperationException>()
.And.Message.Should().Be("The Value property cannot be accessed when errors have been recorded. Check IsError before accessing Value.");
}

[Fact]
Expand Down

0 comments on commit 1f43ff3

Please sign in to comment.