A compact results library similar to FluentResults, offering all essential features for effective error handling and response management.
The library offers four main result types, each suited for different scenarios:
Result
: Indicates a simple success or failure of an operation.Result<T>
: Returns a value if the operation is successful.Result<T, TError>
: Returns a value or a custom error if the operation fails.SuccessOr<TError>
: Indicates success or returns a custom error for operations that do not return a value.
Use Result
to simply indicate the success or failure of an operation.
Result DoWork()
{
if (isOperationSuccessful)
{
return Result.Ok();
}
else
{
return Result.Fail("Operation is unsuccessful");
}
}
Result result = DoWork();
result.IsSuccess;
result.IsFailure;
result.ErrorMessage;
IsSuccess
: Returnstrue
if the operation was successful.IsFailure
Returnstrue
if the operation failed.ErrorMessage
: Provides the error message if the operation failed.
Use Result<T>
when the operation needs to return a value upon success.
Result<int> DoWork()
{
int valueToReturn = 123;
if (isOperationSuccessful)
{
return Result.Ok(valueToReturn);
}
else
{
return Result.Fail("Operation is unsuccessful");
}
}
Result<int> result = DoWork();
result.IsSuccess;
result.IsFailure;
result.Value;
result.ErrorMessage;
IsSuccess
: Indicates if the operation was successful.IsFailure
: Indicates if the operation failed.Value
: The value returned by the operation (e.g., 123).ErrorMessage
: The error message if the operation failed.
Use Result<T, TError>
to return either a value upon success or a custom error if the operation fails.
Result<int, CustomError> DoWork()
{
int valueToReturn = 123;
if (isOperationSuccessful)
{
return Result.Ok(valueToReturn);
}
else
{
return Result.Fail(new CustomError(666, "Error message"));
}
}
public class CustomError
{
public int StatusCode { get; init; }
public string Message { get; init; }
public CustomError(int statusCode, string message)
{
StatusCode = statusCode;
Message = message;
}
}
Result<int, CustomError> result = DoWork();
result.IsSuccess;
result.IsFailure;
result.Value;
result.Error;
IsSuccess
: Whether the operation succeeded.IsFailure
: Indicates if the operation failed.Value
: The value returned if successful.Error
: The custom error returned if the operation failed.
Use SuccessOr<TError>
for operations that don't return a value but may fail with a custom error.
SuccessOr<CustomError> DoWork()
{
if (isOperationSuccessful)
{
return Result.Ok();
}
else
{
return Result.Fail(new CustomError(666, "Error message"));
}
}
SuccessOr<CustomError> result = DoWork();
result.IsSuccess;
result.IsFailure;
result.Error;
IsSuccess
: Indicates if the operation was successful.IsFailure
: Indicates if the operation failed.Error
: The custom error returned if the operation failed.
This project is licensed under the MIT License - see the LICENSE.txt file for details.