Error handling standard¶
This page sets the rules for throwing, catching, logging and mapping exceptions in ConnectSoft services and libraries. It is written for engineers who write or review error paths. The architecture of exception handling (domain exceptions, ProblemDetails, gRPC interceptors, messaging retries) is explained in Exception handling.
Where each failure is logged¶
An exception is logged in at most two places, each with its own purpose:
| Place | What it logs | Level | Rule |
|---|---|---|---|
The catch of a public domain operation |
Every failure of the operation, with the exception attached, before throw; |
Error |
CS-LOG-004 |
| The boundary that maps the exception to a response (ProblemDetails, gRPC status, message retry) | A business refusal mapped to a 4xx | Warning |
CS-ERR-002 |
| The same boundary | An infrastructure failure, whatever status it is mapped to | Error |
CS-ERR-003 |
Rules¶
CS-ERR-001: Never swallow an exception¶
Severity: blocker · Applies to: service, library, api-client, blazor, template · Enforced by: manual · Status: active
Why¶
A swallowed exception turns a failure into a silent success. The caller continues with missing data, the user is told that something happened when it did not, and nothing in the logs explains why.
Do¶
End every catch block in one of these ways:
- rethrow with throw;;
- throw a new, more specific exception with the original as innerException (see CS-ERR-010);
- handle the failure completely, with a fallback that is documented in a comment and logged.
Don't¶
- Write an empty
catchblock, or one that only logs and then continues as if the operation succeeded. - Rethrow with
throw ex;, which loses the original stack trace. - Catch
Exceptionto returnnull,falseor an empty result without logging.
Example¶
// Do
catch (HttpRequestException ex)
{
this.logger.Here(log => log.LogWarning(exception: ex, message: "Customer directory unavailable; showing orders without customer names"));
return orders;
}
// Don't
catch (Exception)
{
}
How to check¶
- Read every
catchblock in the change and check how it ends. - Search for
catch\s*(\(.*\))?\s*\{\s*\}andthrow ex;.
CS-ERR-002: Log a business refusal at the boundary at Warning¶
Severity: minor · Applies to: service, template · Enforced by: manual (target: ENF-034) · Status: active
Why¶
When a domain exception is mapped to a 4xx response, the boundary log entry records what the caller was told: the status, the exception type and the error identifier. Operators use it to see refused requests in production without reading every domain log entry. Warning keeps expected refusals apart from real failures.
Do¶
- In the central exception mapping (ProblemDetails, the gRPC interceptor or the messaging error handler), log every domain exception that is mapped to a 4xx at
Warning. - Include the exception type, the mapped status and the error identifier that is returned to the caller.
Don't¶
- Log a business refusal at
Errorat the boundary. - Log it in each controller or handler instead of in the central mapping.
Example¶
options.Map<OrderNotFoundException>((context, ex) =>
{
var logger = context.RequestServices.GetService<ILogger<OrderNotFoundException>>();
logger?.Here(log => log.LogWarning(
exception: ex,
message: "Request refused with {StatusCode}: {ExceptionType}",
StatusCodes.Status404NotFound,
ex.GetType().Name));
return new ProblemDetails { Status = StatusCodes.Status404NotFound, Title = "Order not found" };
});
How to check¶
- Read the central mapping. Each domain exception mapped to a 4xx is logged at
Warning, once. - The
Warningentry includes the exception type, the mapped status and the error identifier that is returned to the caller. - The base template does not log mapped 4xx results yet (ENF-034).
CS-ERR-003: Classify infrastructure failures by exception type and always log them at Error¶
Severity: major · Applies to: service, template · Enforced by: manual (target: ENF-034) · Status: active
Why¶
A status code says what the caller was told, not whether the server is at fault. When an infrastructure failure, such as a database that does not answer, is mapped to a 4xx status, a logging filter that looks only at status >= 500 drops it. The failure then appears nowhere, and the response carries only an error identifier.
Do¶
- Decide whether a failure is an infrastructure failure by its exception type, searching the whole
InnerExceptionchain, for exampleDbException,ADOException,HttpRequestExceptionorTimeoutException. - Log every infrastructure failure at
Errorwith the exception attached, even when it is mapped to a 4xx. - Put a classification that discloses no data, such as the provider's error number, in the response in every environment. Keep free text behind the Development check.
- Resolve services inside a mapping function with
GetService, so that a missing service does not turn the mapping itself into a 500.
Don't¶
- Decide whether to log by the mapped status code alone.
- Rely on output that appears only in the Development environment. Acceptance hosts often run as Production.
How to check¶
- Read the logging predicate of the exception mapping. It tests exception types through the
InnerExceptionchain, not only the status. The base template relies on the middleware default, which logs only 5xx results (ENF-034). - A test maps a database exception through the ProblemDetails configuration and asserts that it is logged and that the response carries the classification.
CS-ERR-004: Keep problem details mappings from throwing¶
Severity: major · Applies to: service, template · Enforced by: manual · Status: active
Why¶
The problem details middleware swallows an exception thrown inside a mapping function and falls back to its catch-all mapping, which returns HTTP 500. A diagnostic step that cannot resolve a service therefore replaces the status it was meant to explain.
Do¶
- Resolve services in a mapping function with
GetService, and handlenull. - Keep mapping functions free of I/O.
- Cover each mapping with a test that boots a host with the service's own problem details configuration and asserts the status the caller receives.
Don't¶
- Call
GetRequiredServicein a mapping function. - Read a request or response body in a mapping function.
How to check¶
Search mapping functions for GetRequiredService and for I/O calls. Check that a test asserts the status code through a test host, not only that the use case throws.
CS-ERR-005: Map exceptions to responses at the boundary and hide internal details¶
Severity: major · Applies to: service, template · Enforced by: manual · Status: active
Why¶
A domain layer that knows about HTTP or gRPC cannot be reused by another transport. A stack trace or an exception message in a response discloses implementation details to the caller.
Do¶
- Throw domain exceptions from the domain layer.
- Map them to ProblemDetails, gRPC status codes or message retries in one central place per transport.
- Return stack traces and exception messages only in the Development environment.
Don't¶
- Catch exceptions in controllers to build error responses by hand.
- Reference
Microsoft.AspNetCore.Httpor gRPC status types from the domain layer.
How to check¶
- New controllers and gRPC services contain no
try/catchthat builds a response. - New exception types are added to the central mapping.
- Search domain-layer projects in the change for references to
Microsoft.AspNetCore.Httpand to gRPC status types.
CS-ERR-006: Throw specific exception types¶
Severity: minor · Applies to: service, library, api-client, blazor, template · Enforced by: analyzer CA2201 · Status: active
Why¶
A caller can handle only what it can tell apart. new Exception(...) forces callers to catch everything, and the central mapping cannot give it a meaningful status.
Do¶
- Throw a .NET exception that fits, such as
ArgumentException,InvalidOperationExceptionorNotSupportedException. - For a business rule, throw a sealed domain exception named after the failure, for example
OrderNotFoundException, that carries the identifiers involved.
Don't¶
- Throw
Exception,SystemExceptionorApplicationException. - Put personal data in an exception message.
How to check¶
- CA2201 reports reserved exception types. Existing uses are listed under ENF-033.
- Read each new exception message and check that it carries no personal data.
CS-ERR-007: Guard arguments with the ThrowIf helpers¶
Severity: nit · Applies to: service, library, api-client, blazor, template · Enforced by: analyzer CA1510 · Status: active
Why¶
ArgumentNullException.ThrowIfNull and its siblings are shorter, set the parameter name automatically and are the form most ConnectSoft code already uses.
Do¶
- Use
ArgumentNullException.ThrowIfNull(input);at the start of public methods. - Use
ArgumentException.ThrowIfNullOrEmptyandArgumentOutOfRangeException.ThrowIfNegativewhere they fit.
Don't¶
- Write
if (input == null) { throw new ArgumentNullException(nameof(input)); }in new code.
How to check¶
CA1510 reports the long form.
CS-ERR-008: Treat cancellation as cancellation, not as a failure¶
Severity: minor · Applies to: service, library, api-client, blazor, template · Enforced by: manual · Status: active
Why¶
An OperationCanceledException means the caller gave up or the host is stopping. Logging it as an error or counting it as a failure fills dashboards with noise and can trigger retries of work nobody wants.
Do¶
- Let
OperationCanceledExceptionpropagate, or catch it only to stop work cleanly. - When a general
catch (Exception)would also catch it, filter it out withcatch (Exception ex) when (ex is not OperationCanceledException).
Don't¶
- Log cancellation at
Error, or record it in a failure metric.
How to check¶
Read catch (Exception ...) blocks in code that receives a CancellationToken and check how cancellation is treated.
CS-ERR-009: Test a retry policy against the exception the call actually throws¶
Severity: minor · Applies to: service, library, template · Enforced by: manual · Status: active
Why¶
A retry policy keyed on a low-level exception type does nothing when the library it wraps throws its own exception type around the low-level one. The code looks resilient, and the first transient failure is fatal.
Do¶
- Key a retry policy on the exception type the called method actually throws, or inspect the inner exception explicitly.
- Test the policy with that exception, and assert that it retries.
Don't¶
- Assume that a library lets a driver exception, such as
SqlException, pass through unwrapped.
How to check¶
Each retry policy has a test that feeds it the exception the wrapped call throws and asserts a retry.
CS-ERR-010: Keep the original exception when you wrap it¶
Severity: major · Applies to: service, library, blazor, template · Enforced by: manual (analyzer: Meziantou MA0054) · Status: active
Why¶
A wrapping exception without innerException keeps the failure visible but drops what caused it: the original type, message, position and stack trace. Whoever reads the log sees "response was not valid" and cannot tell which byte, field or call failed.
Do¶
- Pass the caught exception as
innerExceptionwhen you throw a new one from acatchblock. - Give your own exception types a constructor that takes
innerException.
Don't¶
- Throw a new exception from a
catchblock without the caught exception. - Suppress MA0054 instead of passing the inner exception.
Example¶
// Do
catch (JsonException ex)
{
throw new OrderImportException("The order file is not valid JSON.", ex);
}
// Don't
catch (JsonException)
{
throw new OrderImportException("The order file is not valid JSON.");
}
How to check¶
- Every
throw newinside acatchblock passes the caught exception. - No
#pragma warning disable MA0054and noMA0054suppression in.editorconfigorNoWarn.