Exceptions and Error Handling¶
Rule prefix: ERR · Baseline: C# 14 / .NET 10 · Levels: DO · DO NOT · CONSIDER · AVOID
Home · Rule index · Naming cheat sheet
This chapter covers how code reports and handles failure: which exception types you throw, how you validate arguments, how you catch and rethrow, how you write a custom exception, how you release disposable resources, and how you give an error a stable code. Exception class names are set by NAM-126. What an exception message and a log entry may contain is set by the security rules on page 13. async error flow is on page 11.
The CA rules in this chapter report in the build at warning, except CA1031, CA1063 and CA1816, which ship as suggestion: process boundaries legitimately catch Exception, and the dispose pattern is a convention that a tool cannot judge case by case. Rules marked Manual are checked in review and listed in the "Manual review only" table on page 15.
Rule index¶
| ID | Level | Rule | Enforced |
|---|---|---|---|
| ERR-010 | DO | throw the most specific existing exception type (ArgumentException, InvalidOperationException, OrderNotFoundException), never Exception, SystemException, ApplicationException or runtime-reserved types such as NullReferenceException and IndexOutOfRangeException. |
CA2201 |
| ERR-011 | DO | rethrow a caught exception with throw; and, when translating it to another exception type, pass the original as the inner exception. |
CA2200 |
| ERR-012 | DO | catch only exception types you can handle, use when filters instead of catching and rethrowing, never leave a catch block empty or return a default without logging (expected cancellation and the Try-pattern translation of ERR-016 excepted), and catch Exception only at a process or request boundary that logs it. |
CA1031, ReSharper: EmptyGeneralCatchClause |
| ERR-013 | DO NOT | throw from property getters, Equals, GetHashCode, ToString, operators == and !=, static constructors or Dispose; return a safe value or use a method instead. |
CA1065 |
| ERR-014 | DO | validate the arguments of public and protected members at entry with the static throw helpers (ArgumentNullException.ThrowIfNull, ArgumentException.ThrowIfNullOrWhiteSpace, ArgumentOutOfRangeException.ThrowIfNegativeOrZero, ObjectDisposedException.ThrowIf). |
CA1510, CA1511, CA1512, CA1513, CA2264, ReSharper: UseThrowIfNullMethod |
| ERR-015 | DO | derive a custom exception from Exception or a more specific BCL exception, make it public, and give it the parameterless, message and message-plus-inner-exception constructors. |
CA1032, CA1064 |
| ERR-016 | DO | report an expected failure, such as invalid user input or a missing optional record, through the Try pattern or a result type, and throw exceptions only for failures the caller cannot reasonably anticipate. | Manual |
| ERR-017 | DO | rethrow an exception that was captured outside its catch block with ExceptionDispatchInfo.Capture(ex).Throw() so the original stack trace survives. |
Manual |
| ERR-018 | DO NOT | catch NullReferenceException, IndexOutOfRangeException, AccessViolationException or other exceptions that signal a defect; fix the defect instead. |
Manual |
| ERR-020 | DO | dispose every IDisposable or IAsyncDisposable object you create or own with using or await using, and dispose disposable fields in the owning type's Dispose. |
CA2000, CA2213 |
| ERR-021 | DO | implement the dispose pattern (protected virtual void Dispose(bool disposing), and a public Dispose() that calls it and then GC.SuppressFinalize(this)) in every unsealed disposable type, add a finalizer only when the type directly owns an unmanaged handle (prefer SafeHandle), and give a sealed type a single public Dispose method. |
CA1063, CA1816 |
| ERR-022 | DO | obtain HttpClient instances from IHttpClientFactory or reuse one long-lived instance, and never create and dispose an HttpClient per request. |
Manual |
| ERR-030 | DO | give every error a stable machine-readable code, declare each code once as a const string in one static class per area, reuse that constant at every call site, and declare the error's message next to its code. |
Manual |
Throwing and catching¶
These rules cover which exceptions to throw, how to validate arguments, and how to catch, rethrow and define exceptions.
ERR-010¶
DO throw the most specific existing exception type (ArgumentException, InvalidOperationException, OrderNotFoundException), never Exception, SystemException, ApplicationException or runtime-reserved types such as NullReferenceException and IndexOutOfRangeException.
✅ Correct
public static void EnsureShippable(Order order)
{
ArgumentNullException.ThrowIfNull(order);
if (order.Lines.Count == 0)
{
throw new InvalidOperationException($"Order {order.Id} has no lines."); // Specific type, no sensitive data
}
}
❌ Incorrect — a general exception type
public static void EnsureShippable(Order order)
{
ArgumentNullException.ThrowIfNull(order);
if (order.Lines.Count == 0)
{
throw new Exception($"Order {order.Id} has no lines."); // general exception type
}
}
Why: A caller can catch only what it can name. Exception forces a catch-all, which also catches defects (ERR-012), and ApplicationException and SystemException carry no meaning of their own. The runtime throws NullReferenceException and IndexOutOfRangeException to signal a defect, so throwing them yourself makes a real defect look like yours. Pick a BCL type when one fits (ArgumentException for a bad argument, InvalidOperationException for a bad state) and write your own when callers need to handle the case (ERR-015).
Scope: Exceptions you throw · Enforced: CA2201 · Sources: MS-FDG-EXCTYPES, MS-EXC, MS-CA, AV
ERR-011¶
DO rethrow a caught exception with throw; and, when translating it to another exception type, pass the original as the inner exception.
✅ Correct — translate and keep the original as the inner exception
public static string ReadImportFile(string path)
{
try
{
return File.ReadAllText(path);
}
catch (IOException ex)
{
throw new InvalidOperationException("The order import file could not be read.", ex); // Inner exception kept
}
}
✅ Correct — undo a partial change, then rethrow with throw;
public static async Task ExportAsync(string path, string content, CancellationToken cancellationToken = default)
{
try
{
await File.WriteAllTextAsync(path, content, cancellationToken);
}
catch (IOException)
{
File.Delete(path); // Compensating action: remove the partial file
throw; // Keeps the original stack trace
}
}
❌ Incorrect — throw ex; and a translation that drops the original
public static string ReadImportFile(string path)
{
try
{
return File.ReadAllText(path);
}
catch (FileNotFoundException ex)
{
throw ex; // resets the stack trace
}
catch (IOException)
{
throw new InvalidOperationException("The order import file could not be read."); // inner exception dropped
}
}
Why: throw ex; restarts the stack trace at the throw line, so the trace no longer shows where the failure began. throw; keeps it, so use it after a compensating action such as removing a partial file. When you translate an exception at a layer boundary, the inner exception keeps the original type, message and trace for whoever reads the log. The message of the new exception follows SEC-072: no secrets, credentials, connection strings or personal data, because the message travels to logs and callers.
Exceptions:
throw;is valid only inside acatchblock. To rethrow an exception you stored earlier, use ERR-017.
Scope: Rethrowing and translating exceptions · Enforced: CA2200 · Sources: MS-EXC, MS-CA, RT-GC
ERR-012¶
DO catch only exception types you can handle, use when filters instead of catching and rethrowing, never leave a catch block empty or return a default without logging (expected cancellation and the Try-pattern translation of ERR-016 excepted), and catch Exception only at a process or request boundary that logs it.
✅ Correct
public static string? ReadNotes(string path, ILogger logger)
{
try
{
return File.ReadAllText(path);
}
catch (IOException ex) when (ex is not FileNotFoundException) // Specific type, filtered
{
logger.LogWarning(ex, "Notes file could not be read");
return null;
}
}
❌ Incorrect — a general catch that swallows the failure — Insecure, do not use
// INSECURE: the catches hide failures, including defects, and return values that look valid
public static string? ReadNotes(string path)
{
try
{
return File.ReadAllText(path);
}
catch (Exception) // general catch that swallows the failure
{
return null; // default returned without logging
}
}
public static void DeleteNotes(string path)
{
try
{
File.Delete(path);
}
catch (IOException) // empty catch block
{
}
}
Why: A catch you cannot act on hides the failure from everyone who could. Returning null makes an unreadable notes file look like a file without notes, and nothing in the log shows that it happened. A when filter runs before the stack unwinds, so a non-matching exception keeps its original stack and you avoid a catch-and-rethrow; here a missing file is a configuration defect and propagates, while other I/O failures are logged and the optional notes are skipped. The log call passes the exception object and a constant template with no file path or other personal data (SEC-073). CA1031 ships as a hint because boundaries legitimately catch it.
Exceptions:
- Expected cancellation (an
OperationCanceledExceptionraised by the caller's token) and the Try-pattern translation of ERR-016, where acatchturns an expected failure into afalseor a result value, may return without logging. - A process entry point or request pipeline catches
Exceptiononce, logs it with the exception object, and returns an error result or exit code. No other layer between the entry point and the failure repeats that catch. - Inside the call chain below that boundary, ERR-018 still applies: do not catch the exception types that signal defects.
Scope: catch clauses · Enforced: CA1031, ReSharper: EmptyGeneralCatchClause · Config: resharper_empty_general_catch_clause_highlighting · Sources: MS-EXC, MS-CONV, MS-FDG-EXCTYPES, MS-CA, AV
ERR-013¶
DO NOT throw from property getters, Equals, GetHashCode, ToString, operators == and !=, static constructors or Dispose; return a safe value or use a method instead.
✅ Correct
namespace Contoso.Orders;
public sealed class OrderKey(int id)
{
public int Id { get; } = id;
public override bool Equals(object? obj) => obj is OrderKey other && other.Id == Id; // Never throws
public override int GetHashCode() => Id;
}
❌ Incorrect — Equals throws
namespace Contoso.Orders;
public sealed class OrderKey(int id)
{
public int Id { get; } = id;
public override bool Equals(object? obj) => throw new InvalidOperationException("Compare by Id."); // Equals throws
public override int GetHashCode() => Id;
}
Why: Collections, debuggers and logging call these members without a try. A throwing Equals or GetHashCode breaks a Dictionary lookup at an unrelated call site, and a throwing Dispose hides the exception that caused the cleanup. A getter that can fail is a method in disguise (VAR-526).
Exceptions:
- A setter or an indexer validates its input and may throw
ArgumentException; this rule covers getters and the members in the statement.
Scope: Members that callers do not expect to throw · Enforced: CA1065 · Sources: MS-FDG-PROPERTY, MS-CA
ERR-014¶
DO validate the arguments of public and protected members at entry with the static throw helpers (ArgumentNullException.ThrowIfNull, ArgumentException.ThrowIfNullOrWhiteSpace, ArgumentOutOfRangeException.ThrowIfNegativeOrZero, ObjectDisposedException.ThrowIf).
✅ Correct — argument guards
public static decimal CalculateLineTotal(OrderLine line)
{
ArgumentNullException.ThrowIfNull(line); // Guard clause at entry
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(line.Quantity);
return line.Amount;
}
✅ Correct — string and disposed-object guards
private bool _isClosed;
public string Normalize(string code)
{
ObjectDisposedException.ThrowIf(_isClosed, this);
ArgumentException.ThrowIfNullOrWhiteSpace(code);
return code.Trim().ToUpperInvariant();
}
public void Close() => _isClosed = true;
❌ Incorrect — a hand-written null guard
public static decimal CalculateLineTotal(OrderLine line)
{
if (line is null) // hand-written null guard
{
throw new ArgumentNullException(nameof(line));
}
return line.Amount;
}
Why: A guard clause at the top of a member fails before the member changes any state, and the exception names the parameter that caused it. The static helpers read the parameter name from the call site, so the name cannot go stale in a rename, and the throw sits in a separate method, which keeps the guarded member small. CA1510 reports a hand-written null check, CA1511 an empty-string check, CA1512 a range check and CA1513 a disposed check; CA2264 reports a non-nullable value passed to ThrowIfNull, where the guard can never fire. CA1062 reports every unguarded dereference of a public parameter; it is noisy at warning, so it ships at suggestion.
Exceptions:
- Private and internal members trust their callers in the same assembly. Validate once at the public entry point and rely on nullable annotations behind it.
- Examples on other rules omit argument guards unless the rule is about them (see the README fragment convention).
Scope: Arguments of public and protected members · Enforced: CA1510, CA1511, CA1512, CA1513, CA2264, ReSharper: UseThrowIfNullMethod · Config: resharper_use_throw_if_null_method_highlighting · Sources: MS-EXC, MS-FDG-PARAMDESIGN, MS-CA, RS-INSPECT
ERR-015¶
DO derive a custom exception from Exception or a more specific BCL exception, make it public, and give it the parameterless, message and message-plus-inner-exception constructors.
✅ Correct
namespace Contoso.Orders;
public sealed class OrderImportException : Exception // Public, derives from Exception
{
public OrderImportException()
{
}
public OrderImportException(string message)
: base(message)
{
}
public OrderImportException(string message, Exception innerException)
: base(message, innerException)
{
}
}
❌ Incorrect — only the message constructor
namespace Contoso.Orders;
public sealed class OrderImportException : Exception // standard constructors missing
{
public OrderImportException(string message)
: base(message)
{
}
}
Why: The three constructors are the shape every .NET exception has, so a caller can create yours the same way as any other and wrap a lower-level failure with it. The class is public so that callers outside the assembly can catch it by type. Create a custom exception only when a caller handles the case differently from the existing types; the name ends with Exception (NAM-126).
Exceptions:
- Do not add the legacy serialization constructor
(SerializationInfo, StreamingContext); binary serialization of exceptions is obsolete. - Leave the class unsealed only when you document it as a base class for further exceptions (TYPE-013).
Scope: Custom exception classes · Enforced: CA1032, CA1064 · Sources: MS-EXC, MS-FDG-TYPES, MS-CA
ERR-016¶
DO report an expected failure, such as invalid user input or a missing optional record, through the Try pattern or a result type, and throw exceptions only for failures the caller cannot reasonably anticipate.
✅ Correct
public static bool TryParseQuantity(string text, out int quantity)
{
return int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out quantity) && quantity > 0;
}
public static string Describe(string text)
{
if (TryParseQuantity(text, out int quantity))
{
return $"Quantity {quantity}";
}
return "Enter a whole number greater than zero."; // Expected failure: a branch, not an exception
}
❌ Incorrect — exceptions for normal flow
public static int ParseQuantity(string text) => int.Parse(text, CultureInfo.InvariantCulture);
public static string Describe(string text)
{
try
{
return $"Quantity {ParseQuantity(text)}";
}
catch (FormatException) // exceptions for normal flow
{
return "Enter a whole number greater than zero.";
}
}
Why: Mistyped input is routine, not exceptional. A bool return costs nothing and reads as a branch, while an exception unwinds the stack and captures a stack trace, and it also fills logs with entries that are not faults. Reserve exceptions for failures the caller cannot reasonably anticipate, such as a corrupt file or a broken invariant.
Exceptions:
- A constructor cannot return
false, so it throws; offer a staticTryCreatemethod when callers expect to pass invalid input.
Scope: Failures callers expect to happen · Enforced: Manual · Sources: MS-FDG-EXCTHROW, MS-EXC, AV
ERR-017¶
DO rethrow an exception that was captured outside its catch block with ExceptionDispatchInfo.Capture(ex).Throw() so the original stack trace survives.
✅ Correct
private System.Runtime.ExceptionServices.ExceptionDispatchInfo? _failure;
public void Fail(Exception exception)
{
_failure = System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(exception); // Keeps the trace
}
public void ThrowIfFailed() => _failure?.Throw();
❌ Incorrect — a stored exception thrown with throw
private Exception? _failure;
public void Fail(Exception exception) => _failure = exception;
public void ThrowIfFailed()
{
if (_failure is not null)
{
throw _failure; // stack trace lost
}
}
Why: throw always writes the current location into the stack trace, so an exception thrown from a field shows the line of ThrowIfFailed and not the line of the original failure. ExceptionDispatchInfo stores the trace and appends the new location to it when you call Throw().
Exceptions:
awaitandGetAwaiter().GetResult()already preserve the stack trace of a faulted task. UseExceptionDispatchInfoonly when you store the exception yourself.
Scope: Exceptions captured in one place and rethrown in another · Enforced: Manual · Sources: MS-EXC
ERR-018¶
DO NOT catch NullReferenceException, IndexOutOfRangeException, AccessViolationException or other exceptions that signal a defect; fix the defect instead.
✅ Correct
public static OrderLine? GetLineAt(OrderLine[] lines, int index)
{
ArgumentNullException.ThrowIfNull(lines);
return index >= 0 && index < lines.Length ? lines[index] : null; // Check the bounds, do not catch
}
❌ Incorrect — catching a defect
public static OrderLine? GetLineAt(OrderLine[] lines, int index)
{
try
{
return lines[index];
}
catch (IndexOutOfRangeException) // catching a defect
{
return null;
}
}
Why: These exceptions mean the code is wrong: a reference that should not be null, an index that should have been checked. Catching them turns a defect into silent bad data and hides the line that needs fixing. A corrupted-state exception such as AccessViolationException means process memory can no longer be trusted, so the only safe action is to let the process end. On .NET Core and later the runtime does not deliver AccessViolationException to a catch block at all, so such a catch is dead code.
Exceptions:
- A process boundary may catch
Exceptionto log a defect and end the operation (ERR-012).
Scope: Exceptions that signal defects or corrupted state · Enforced: Manual · Sources: MS-FDG-EXCTYPES, MS-EXC, MS-CA
Disposal¶
These rules cover disposing objects, the dispose pattern and the lifetime of HttpClient.
ERR-020¶
DO dispose every IDisposable or IAsyncDisposable object you create or own with using or await using, and dispose disposable fields in the owning type's Dispose.
✅ Correct — locals
public static async Task<string> ReadAsync(string path, CancellationToken cancellationToken = default)
{
using StreamReader reader = File.OpenText(path); // Disposed at the end of the method
return await reader.ReadToEndAsync(cancellationToken);
}
public static async Task<bool> HasRowsAsync(System.Data.Common.DbCommand command,
CancellationToken cancellationToken = default)
{
await using System.Data.Common.DbDataReader reader = await command.ExecuteReaderAsync(cancellationToken);
return await reader.ReadAsync(cancellationToken);
}
✅ Correct — a field
namespace Contoso.Orders;
public sealed class OrderExport(string path) : IDisposable
{
private readonly FileStream _stream = File.OpenRead(path); // Owned field
public long Length => _stream.Length;
public void Dispose() => _stream.Dispose(); // Disposed by the owner
}
❌ Incorrect — a local that is never disposed and a disposable field that Dispose never disposes (the client created per call also breaks ERR-022; this example marks the disposal only)
namespace Contoso.Orders;
public sealed class OrderExport : IDisposable
{
private readonly FileStream _stream = File.OpenRead("orders.csv"); // disposable field not disposed
public static Uri? GetServer()
{
var client = new HttpClient(); // created and never disposed
return client.BaseAddress;
}
public void Dispose() { }
}
❌ Incorrect — an async reader that is never disposed
public static async Task<bool> HasRowsAsync(System.Data.Common.DbCommand command,
CancellationToken cancellationToken = default)
{
System.Data.Common.DbDataReader reader = await command.ExecuteReaderAsync(cancellationToken); // never disposed
return await reader.ReadAsync(cancellationToken);
}
Why: A disposable object holds an operating-system resource such as a file handle, a socket or a connection, and a missed Dispose keeps it until a finalizer runs, if there is one. A using declaration releases it on every exit path, including an exception (VAR-551, VAR-552). CA2000 reports a local that is not disposed and CA2213 a disposable field that Dispose does not dispose. CA2000 tracks some types only: it reports an HttpClient local but not a FileStream or MemoryStream local, so reviewers check the rest. Data-access code follows the same rule: dispose a DbDataReader, or a context created by IDbContextFactory, with await using.
Exceptions:
- Do not dispose an object you do not own: a service injected by the container, a client from
IHttpClientFactory, or a command passed in as an argument, ascommandis above.
Scope: IDisposable and IAsyncDisposable objects you create or own · Enforced: CA2000, CA2213 · Sources: MS-CONV, MS-EXC, MS-CA
ERR-021¶
DO implement the dispose pattern (protected virtual void Dispose(bool disposing), and a public Dispose() that calls it and then GC.SuppressFinalize(this)) in every unsealed disposable type, add a finalizer only when the type directly owns an unmanaged handle (prefer SafeHandle), and give a sealed type a single public Dispose method.
✅ Correct — a sealed type has a single public Dispose
namespace Contoso.Orders;
public sealed class AuditLog(string path) : IDisposable // Sealed: a single public Dispose
{
private readonly StreamWriter _writer = File.AppendText(path);
public void Write(string message) => _writer.WriteLine(message);
public void Dispose() => _writer.Dispose();
}
✅ Correct — an unsealed type has the dispose pattern and no finalizer
namespace Contoso.Orders;
public class AuditLog(string path) : IDisposable // Designed as a base class: subclasses override Dispose(bool)
{
private readonly StreamWriter _writer = File.AppendText(path);
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_writer.Dispose();
}
}
}
❌ Incorrect — an unsealed class without the dispose pattern
namespace Contoso.Orders;
public class AuditLog(string path) : IDisposable // unsealed without the dispose pattern
{
private readonly StreamWriter _writer = File.AppendText(path);
public void Write(string message) => _writer.WriteLine(message);
public void Dispose() => _writer.Dispose();
}
Why: A subclass of an unsealed type can add its own resources, and it can release them only through a protected virtual void Dispose(bool disposing) hook that the base type calls from its public Dispose(). A sealed type has no subclass and needs only the public method. A finalizer is a different matter: add one only for an unmanaged handle the type owns directly, because a finalizer on every disposable type slows garbage collection. CA1063 reports the unsealed class above on its type line, and CA1816 checks the GC.SuppressFinalize call. CA1063 and CA1816 ship as hints.
Exceptions:
- A type that directly owns an unmanaged handle adds a finalizer that calls
Dispose(disposing: false). Wrap the handle in aSafeHandlewhere you can, so that the type needs no finalizer.
Scope: Types that implement IDisposable · Enforced: CA1063, CA1816 · Sources: MS-CA, MS-EXC
ERR-022¶
DO obtain HttpClient instances from IHttpClientFactory or reuse one long-lived instance, and never create and dispose an HttpClient per request.
✅ Correct
namespace Contoso.Orders;
public sealed class CarrierClient(HttpClient httpClient) // A typed client: the factory supplies and manages it
{
public Task<string> GetStatusAsync(CancellationToken cancellationToken = default)
{
return httpClient.GetStringAsync(new Uri("https://carrier.example.com/status"), cancellationToken);
}
}
❌ Incorrect — a new client for every request
public static async Task<string> GetStatusAsync(CancellationToken cancellationToken = default)
{
using var client = new HttpClient(); // new client per request exhausts sockets
return await client.GetStringAsync(new Uri("https://carrier.example.com/status"), cancellationToken);
}
Why: Disposing an HttpClient does not release its connection at once; the socket stays in the operating system's wait state, so a service that creates a client per request runs out of sockets under load. A typed client registered with AddHttpClient<CarrierClient>() (package Microsoft.Extensions.Http) lets the factory pool and recycle the handlers. The CA2000 rule in ERR-020 does not apply to factory clients, because the factory owns them.
Exceptions:
- An application without dependency injection may keep one
HttpClientin astatic readonlyfield and create it with aSocketsHttpHandlerwhosePooledConnectionLifetimeis set, so the client follows DNS changes.
Scope: HttpClient instances · Enforced: Manual · Sources: MS-CA, AV
Error codes¶
This rule covers how an error is identified: a code that stays the same when the message changes.
ERR-030¶
DO give every error a stable machine-readable code, declare each code once as a const string in one static class per area, reuse that constant at every call site, and declare the error's message next to its code.
✅ Correct
namespace Contoso.Orders;
public static class PaymentErrors // One class per area
{
public const string AmountMismatch = "payment.amount_mismatch"; // The code, declared once
public const string AmountMismatchMessage = "The payment amount does not match the order total."; // Its message, next to it
public const string CardDeclined = "payment.card_declined";
public const string CardDeclinedMessage = "The card was declined.";
}
public static class PaymentChecks
{
public static (string Code, string Message)? FindAmountError(Order order, Payment payment)
{
if (payment.Amount != order.Total)
{
return (PaymentErrors.AmountMismatch, PaymentErrors.AmountMismatchMessage); // The constants, not literals
}
return null;
}
public static (string Code, string Message)? FindCaptureError(Order order, Payment payment)
{
if (payment.Amount > order.Total)
{
return (PaymentErrors.AmountMismatch, PaymentErrors.AmountMismatchMessage); // Same constants at every call site
}
return null;
}
}
❌ Incorrect — codes and messages written as literals at each call site
public static class PaymentChecks
{
public static (string Code, string Message)? FindAmountError(Order order, Payment payment)
{
if (payment.Amount != order.Total)
{
return ("payment.amount_mismatch", "The payment amount is wrong."); // literal code and a message that exists only here
}
return null;
}
public static (string Code, string Message)? FindCaptureError(Order order, Payment payment)
{
if (payment.Amount > order.Total)
{
return ("payment.amount_missmatch", "Amount does not match."); // the same code, spelled differently
}
return null;
}
}
Why: A caller, a client or a log search needs something to match on that does not change when someone rewords or translates the message. RFC 9457 (problem details for HTTP APIs) rests on the same idea: the type member is the primary identifier of a problem, the detail text is for people and clients should not parse it, and extension members may carry more data. ASP.NET Core writes problem details for API errors and lets you customize them, so at an HTTP boundary a code from this rule can travel as an extension member of the problem details. An anticipated failure is reported by a return value (ERR-016), as in the example, and the code travels with it; an exception can carry the code the same way for a failure the caller cannot anticipate. A const string declared once in one class per area gives every use the same spelling: the compiler rejects a mistyped constant name, a search for the constant finds every place that raises the error, and the code can be used in a switch or an attribute. Putting the message in the same class keeps the text in one place, and a change to either is a change to both. Messages follow SEC-072: no secrets, credentials or personal data. A code is visible to whoever sees the response, so it reveals no more than the message may: failures of authentication and of authorization that reach unauthenticated clients share one generic code, because separate codes for an unknown user and a wrong password let a caller find out which accounts exist. The naming rules apply to the constant's name, which is PascalCase like any constant (NAM-214), and not to its value, which is data, so a snake_case value does not break NAM-016.
The value format is a CONSIDER-level suggestion: write the value as <area>.<reason_in_snake_case> (payment.card_declined). The area groups codes by owner, the reason reads without a lookup table, and lower-case letters, digits, dots and underscores survive logs, URLs and JSON without escaping. Once a code is released, treat it as part of the contract: do not rename it and do not reuse it for another meaning.
The reasoning (a stable identifier kept apart from the text) comes from RFC 9457 and the ASP.NET Core documentation. The one-class-per-area layout, the const string form and the value format are house conventions: neither source prescribes them. No analyzer checks any of it, so this is a manual rule.
Exceptions:
- Argument guards (ERR-014) and exceptions that signal a defect (ERR-018) need no code, because no caller or client tells them apart.
- A code that an external system returns (a payment gateway, for example) is mapped to a code of your own at the boundary; keep the external value as data and do not reuse it as the constant.
Scope: Errors that a caller handles, a client receives or a log search must tell apart · Enforced: Manual · Sources: IETF-RFC9457, MS-ASPNET-ERRORS
Related¶
- NAM-126: the
Exceptionsuffix of a custom exception class. - TYPE-013: when a class stays unsealed.
- VAR-526: when a member is a method and not a property.
- VAR-551 and VAR-552: the
usingandawait usingdeclaration forms. - SEC-072 and SEC-073: what exception messages and log entries may contain.
- NAM-214: the PascalCase name of a constant, which is the name rule that applies to an error-code constant (ERR-030).
- Page 11: error flow in
asyncmethods.
Sources¶
AV · MS-CA · MS-CONV · MS-EXC · MS-FDG-EXCTHROW · MS-FDG-EXCTYPES · MS-FDG-PARAMDESIGN · MS-FDG-PROPERTY · MS-FDG-TYPES · IETF-RFC9457 · MS-ASPNET-ERRORS · RS-INSPECT · RT-GC
Previous: Comments and Documentation · Home · Next: Async and Concurrency