OperationResult: Explicit Success and Failure in .NET
Model success, failure, warnings and payloads with OperationResult, then chain and log results.
Applies to H.Necessaire 4.0.5.
Every non-trivial app has operations that can fail: validating an order, calling a service, parsing a file. Returning null or a bool says that something failed but not why, and exceptions are heavy for failures you fully expect. OperationResult says whether an operation succeeded and, if not, why. It is the currency of the whole library: storage services, QD action processors and safe-execution helpers all return it.
Install
dotnet add package H.NecessaireThe model
class OperationResult
{
bool IsSuccessful // defaults to true
string Reason
string[] Comments
string[] Warnings
string[] ReasonsToDisplay // safe-for-end-users messages
}
class OperationResult<T> : OperationResult
{
T Payload
}Creating results
OperationResult ok = OperationResult.Win();
OperationResult bad = OperationResult.Fail("The order has no items");
OperationResult more = OperationResult.Fail("Rejected", "Missing address", "Missing email"); // reason + comments
// From an exception: flattens inner exceptions into comments
OperationResult fromEx = OperationResult.Fail(exception, "Could not save the order");
// From a list of errors: one error becomes the reason, several become comments
OperationResult many = OperationResult.Fail(new[] { "Name is empty", "Email is invalid" });
// Add a payload (or explicitly none) to get the generic flavour
OperationResult<Order> withOrder = OperationResult.Win().WithPayload(order);
OperationResult<Order> noOrder = OperationResult.Fail("Not found").WithoutPayload<Order>();Implicit conversions
For terse code, results convert implicitly from the most common shapes:
OperationResult a = true; // Win
OperationResult b = false; // Fail
OperationResult c = "Name is required"; // Fail with that reason (an empty string is a Win)
OperationResult d = (isValid, "Checked"); // (bool, reason) tuple
OperationResult<Order> e = order; // Win with payload
OperationResult<Order> f = "Order not found"; // Fail, no payload
if (!someResult) { /* ... */ } // converts to bool via IsSuccessfulConsuming results
OperationResult<Order> validation = ValidateOrder(order);
if (!validation.IsSuccessful)
{
Console.WriteLine(validation); // "FAIL because The order has no items"
foreach (string reason in validation.FlattenReasons())
Console.WriteLine(reason); // reason first, then comments
return;
}
Save(validation.Payload);ToString() prints SUCCESS or FAIL because ..., truncating long reasons, which makes results pleasant to log.
Warnings and user-facing messages
A successful result can still carry warnings, and a failure can carry messages meant for end users, separate from the technical reason:
return OperationResult
.Win()
.WithPayload(invoice)
.Warn("Customer has no VAT number on file");
return OperationResult
.Fail("Payment gateway returned 502")
.Display("We couldn't process your payment. Please try again.");When you do want an exception
Order validOrder = ValidateOrder(order).ThrowOnFailOrReturn();
saveResult.ThrowOnFail();A failed result throws an OperationResultException (generic form: OperationResultException<T>), which extends AggregateException: the reason is the message, each comment becomes an inner exception, and OperationResult exposes the original result.
Chaining
Extension methods let you string dependent steps together and stop at the first failure:
OperationResult result =
await ValidateAsync(order)
.Then(() => ReserveStockAsync(order))
.Then(() => ChargeAsync(order));
OperationResult<Receipt> receipt =
await LoadOrderAsync(id)
.Then(order => BuildReceiptAsync(order));Related helpers: UnwrapToFirstFailOrLastWin() and DeepUnwrapToFirstFailOrLastWin() flatten nested results such as OperationResult<OperationResult<T>>.
Logging results
await SaveAsync(order).LogError(logger, "save the order");
await SendEmailAsync(order).LogWarning(logger, "send the confirmation email");These log only when the result failed (or, for LogWarning, when a successful result has warnings). To keep an expected failure out of the logs, call .DoNotLog() on it first.
When not to use it
Genuine bugs and corrupted state should still throw. Use OperationResult for failures you anticipate and want callers to handle, and let HSafe (see the safe execution article) turn the exceptions from third-party code into results at the boundary.