-
Notifications
You must be signed in to change notification settings - Fork 0
ResultObjects
ResultObjects provide a simple and easy to use object Result
to handle state of applications. This minimizes the use of Exceptions
, which is bad for application performance.
ResultObjects belong in the application-layer of the architecture. We do not recommend adding this to neither domains, nor primitives.
dotnet add package Arcturus.ResultObjects
Result objects have a state where Result.IsSuccess
is either true/false as well as Result.IsFailure
will become the opposite true/false.
Calling .Success()
will automatically set Result.IsSuccess
to true, and .Failure()
will automatically set Result.IsSuccess
to false.
To use the library, simply define a result using the API:
// defines a value-less success result
var successResult = Result.Success();
Use the generic API to provide a value of the result. The value is available from the Result.Value
property.
// defines a value-based success result
// successResult would be of type Result<ReturnValue>
var successResult = Result.Success(new ReturnValue() { ... });
When things go bad, you can use the failure API to provide a failed response. Fail responses do not handle values, as there is not reason to pass along the value of a failed operation.
// defines a value-less failure result
var failedResult = Result.Failure();
// define a value-less failure result of generic type
var failedResult = Result.Failure<ReturnValue>();
To help provide context and information, failures can hold a Fault
reason.
var failedResult = Result.Failure<ReturnValue>(Fault.From("ReturnValue is missing a correct state."));
Fault
objects hold two properties.
property | type | description |
---|---|---|
Code | string | Optional. A system specific code of the fault. |
Message | string | Required. A human friendly message of the fault. |
Specialized faults provide response, by setting an http status code of the resulting Result object. This enables a minimal design when returning fault using the implicit operator.
fault | corresponding status code |
---|---|
AmbiguousFault | Ambiguous |
BadRequestFault | BadRequest |
ConflictFault | Conflict |
ConstraintFault | UnprocessableContent |
ForbiddenFault | Forbidden |
PaymentFault | Payment |
UnauthorizedFault | Unauthorized |
Result objects have two extensions allowing to provide further state.
Allows passing on a captured exception.
try {
// do action that throws an exception
...
return Result.Success();
}
catch (Exception e)
{
return Result
.Failure(new Fault("error", e.Message))
.WithException(new Exception("Error"));
}
Allows assigning a Http status code to the result. This is extremely useful when using the ASP.NET Core extension to provide response results.
return Result
.Failure(Fault.From("error", e.Message))
.WithHttpStatusCode(System.Net.HttpStatusCode.BadRequest)
.WithException(new Exception("Error"));