Skip to content

Handle Errors

Daniel Dieckmann edited this page Nov 6, 2026 · 4 revisions

Handle Errors

Last verified against v3.0.0

Every operation that can fail returns FluentResults.Result<T>. Business failures never throw — the result carries success state, and on failure an IntegrationError with a machine-readable Code, an ErrorType, and the original Exception when one was wrapped. Inspect the result rather than wrapping calls in try/catch.

var header = new LedgerJournalHeader
{
    DataAreaId = "USMF",
    JournalName = "GenJrn",
    Description = "April accruals",
};

Result<LedgerJournalHeader> result = await mediator
    .Send(new CreateCommand<LedgerJournalHeader>(header), cancellationToken)
    .ConfigureAwait(false);

if (result.IsSuccess)
{
    LedgerJournalHeader created = result.Value;
    logger.LogInformation("Created journal {BatchNumber}", created.JournalBatchNumber);
}
else
{
    IntegrationError? error = result.GetError();
    logger.LogWarning("Create failed: [{Type} {Code}]", error?.Type, error?.Code);
}

result.GetError() returns the first IntegrationError from the result, or null if the result carries none. Use it consistently — never hand-roll a LINQ query over result.Errors.

Read the error

IntegrationError extends FluentResults.Error with three members. Deep-linked source: IntegrationError.cs.

Member What it holds
Code Machine-readable, dotted-segment string — Validation.Error, LedgerJournalHeader.NotFound. Match on the prefix.
Type An ErrorType for HTTP-status and log-level mapping.
Exception The wrapped exception when the failure originated from one; otherwise null.

When an exception is passed, the constructor calls CausedBy(exception), so FluentResults' own Reasons chain surfaces it too.

The four ErrorType values

ErrorType has exactly four members. There are no others.

ErrorType Meaning Typical HTTP status
Failure General or unexpected failure (the default) 500
Validation Input rejected by the ValidationBehaviour 400
NotFound No entity matched the composite key 404
Conflict Duplicate, concurrency clash, or domain-rule breach 409

Map to an HTTP response by switching on Type:

IntegrationError? error = result.GetError();

HttpResponseData response = error?.Type switch
{
    ErrorType.Validation => req.CreateResponse(HttpStatusCode.BadRequest),
    ErrorType.NotFound   => req.CreateResponse(HttpStatusCode.NotFound),
    ErrorType.Conflict   => req.CreateResponse(HttpStatusCode.Conflict),
    _                    => req.CreateResponse(HttpStatusCode.InternalServerError),
};

Pattern-match with Match

Match collapses both branches into one expression and always hands onFailure a non-null IntegrationError. If a failed result somehow carries no IntegrationError, Match synthesises IntegrationError("Unknown", <message>, ErrorType.Failure) so your delegate never dereferences null.

string summary = result.Match(
    onSuccess: created => $"Created {created.JournalBatchNumber}",
    onFailure: error => $"Failed: [{error.Type} {error.Code}]");

A batch command returns Result<BatchOutcome> (since v3.0.0), so it uses the same generic overload. A batch that ran hands onFailure a BatchIntegrationError carrying the per-item outcome; a batch rejected before sending (empty list, bad key) hands it a plain Validation error:

Result<BatchOutcome> batchResult = await mediator
    .Send(new CreateBatchCommand<LedgerJournalLine>(lines), cancellationToken)
    .ConfigureAwait(false);

string summary = batchResult.Match(
    onSuccess: outcome => $"Created {outcome.Succeeded} lines",
    onFailure: error => error is BatchIntegrationError batchError
        ? $"{batchError.Outcome.Failed} of {batchError.Outcome.Total} lines failed"
        : $"Batch rejected before sending: {error.Code}");

The non-generic overload matches a valueless Result — for example from a custom ICommand handler or IService<T>.DeleteAsync. See Send Commands for reading the failure list item by item.

Concrete D365 rejections

Each downstream rejection reaches you as a failed Result<T> with a distinct Code and Type. None throws.

Read-only field on update — 403

D365 marks several LedgerJournalHeader fields read-only after create: JournalName, IsPosted, JournalTotalDebit, JournalTotalCredit, and AccountingCurrency. Each carries [ODataField(IgnoreOnUpdate = true)], so the serialiser drops it from the PATCH payload.

Warning

If even one IgnoreOnUpdate field reaches the payload, D365 rejects the whole PATCH with HTTP 403 (ODataSecurityException, "update not allowed for field 'X'") — not only that field. Audit every field against D365's update semantics before shipping an entity. The failed Result<T> surfaces as {Entity}.Unauthorized, a Failure-typed IntegrationError whose Exception holds the client exception.

Result<LedgerJournalHeader> result = await mediator
    .Send(new UpdateCommand<LedgerJournalHeader>(header), cancellationToken)
    .ConfigureAwait(false);

if (result.IsFailed)
{
    IntegrationError? error = result.GetError();
    // error.Code == "LedgerJournalHeader.Unauthorized"; error.Exception carries the ODataClientException (HTTP 403).
    logger.LogError(error?.Exception, "Update rejected: [{Code}]", error?.Code);
}

Validation — 400

The ValidationBehaviour runs before the handler and returns the first validation failure as a fixed shape — IntegrationError("Validation.Error", <first message>, ErrorType.Validation). Later failures are dropped. See Add Validation.

if (result.IsFailed && result.GetError()?.Type == ErrorType.Validation)
{
    // Code is always "Validation.Error"; Message is the first FluentValidation failure.
    return req.CreateResponse(HttpStatusCode.BadRequest);
}

Authentication — 401

An OAuth token-acquisition failure returns IntegrationError("Auth.Msal.{code}", "Token acquisition failed", ErrorType.Failure, ex) from the authenticator, where {code} is the MSAL error code and ex is the MSAL exception. On the HTTP path the ODataAuthenticationHandler short-circuits with a 401 whose ReasonPhrase is the fixed string "Authentication failed", so a single-entity command or query surfaces it as {Entity}.Unauthorized (for example LedgerJournalHeader.Unauthorized) with the generic message "Authentication or authorisation failure", and a batch reports StatusCode 401 on each item. See Authentication Modes.

Warning

Never copy error.Message or error.Exception detail into an HTTP ReasonPhrase or response body — tenant IDs, MSAL/AADSTS codes, and D365 inner-error payloads leak that way. Return a generic message to the caller and log the full error server-side only.

Raise an error from a custom handler

Return a failed result with Result.Fail — do not throw for a business rule:

return Result.Fail<LedgerJournalHeader>(new IntegrationError(
    code: "Journal.AlreadyPosted",
    message: "Cannot modify a posted journal.",
    type: ErrorType.Conflict));

Pass the exception when wrapping one, so the stack is preserved:

catch (ODataClientException ex)
{
    return Result.Fail<LedgerJournalHeader>(new IntegrationError(
        code: "OData.RequestFailed",
        message: ex.Message,
        type: ErrorType.Failure,
        exception: ex));
}

To propagate a downstream failure verbatim — keeping every IError, including the original IntegrationError — pass the error list straight through:

Result<IEnumerable<LedgerJournalHeader>> upstream = await service
    .FindAsync(filter, cancellationToken)
    .ConfigureAwait(false);

if (upstream.IsFailed)
{
    return Result.Fail<DimensionFormat>(upstream.Errors);
}

What still throws

ODataService<T> catches what goes wrong below it on a single-entity operation and returns a failed result instead: a timeout becomes {Entity}.Timeout, cancellation {Entity}.Cancelled, an unrecognised exception (for example a translator NotSupportedException) {Entity}.UnexpectedError — all ErrorType.Failure, with the exception in error.Exception.

These still reach you as exceptions:

  • Your own cancellation during a batch. Cancelling the CancellationToken you passed propagates OperationCanceledException. A failed chunk send does not throw — an HttpClient timeout included, it comes back as failed items with StatusCode 0.
  • GetDimensionOrdersQuery against a non-hyphen delimiter. ArgumentOutOfRangeException — see Known Limitations.
  • Direct IODataClientAdapter calls. The adapter throws ArgumentException for a key value containing a control character, an invalid entity-set name, or a malformed composite-key field name (since v3.0.0 for control characters and entity sets).
  • Genuine bugs — a NullReferenceException in your own handler.

LoggingBehaviour logs an unhandled exception at Error level and re-throws it. Polly absorbs transient HTTP faults before they reach either path; see Configure Resilience.

See Also

Clone this wiki locally