IC Improve Code Recipes

Recipe 5.3 · C#

Custom Exceptions Worth Having

Problem

Some code bases have no custom exceptions, so everything is Exception("Customer not found") and callers parse messages to decide what to do. Others have one exception class per method, sixty of them, none of which any caller catches. Neither helps.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
// Not this: callers have to compare strings.
if (customer == null)
    throw new Exception("Customer not found");

// ...and somewhere up the stack:
catch (Exception ex)
{
    if (ex.Message.Contains("not found"))
        Response.StatusCode = 404;
}

The improved recipe

Write a small set of exceptions that map to decisions a caller actually makes: not found, conflict, business rule violated. Give them a stable error code and the data a handler needs.

C#
using System;

namespace ImproveCode.Errors;

/// <summary>Base type for failures the application expects
/// and knows how to report.</summary>
public abstract class AppException : Exception
{
    protected AppException(
        string errorCode, string message, Exception? inner = null)
        : base(message, inner)
    {
        ErrorCode = errorCode;
    }

    /// <summary>Stable, machine-readable code, e.g. "not_found".
    /// </summary>
    public string ErrorCode { get; }
}

public sealed class NotFoundException : AppException
{
    public NotFoundException(string entity, object key)
        : base("not_found", $"{entity} '{key}' was not found.")
    {
        Entity = entity;
        Key = key;
    }

    public string Entity { get; }

    public object Key { get; }
}

public sealed class ConflictException : AppException
{
    public ConflictException(string message, Exception? inner = null)
        : base("conflict", message, inner)
    {
    }
}

public sealed class BusinessRuleException : AppException
{
    public BusinessRuleException(string rule, string message)
        : base(rule, message)
    {
    }
}

Usage:

C#
Customer customer = await repository.FindAsync(id, ct)
    ?? throw new NotFoundException(nameof(Customer), id);

if (order.Total > customer.CreditLimit)
{
    throw new BusinessRuleException(
        "credit_limit_exceeded",
        $"Order total {order.Total:C} exceeds the credit limit.");
}

How it works

The test for whether an exception class is worth having is simple: does some caller catch it, or does the global handler treat it differently? NotFoundException becomes HTTP 404, ConflictException becomes 409 (a concurrent update, a duplicate key), BusinessRuleException becomes 422. Everything else is a 500. Three classes cover most of what a line-of-business app needs.

The common base class lets the global handler (Recipe 5.4) recognize every expected failure with one type check, and ErrorCode gives API clients something stable to switch on. Messages get reworded; codes shouldn't.

The messages are safe to show to the user because the code that throws them writes them for that purpose. That is the real distinction: an AppException message is part of your product, while a SqlException message is an internal detail that must never reach the browser.

Wrapping a database exception into ConflictException (for example, catching a unique-key violation, SQL Server error 2627 or 2601, and rethrowing) keeps the inner exception for the log and gives the caller a meaningful type.

Variations and pitfalls

  • Use the built-in types when they fit: ArgumentException and ArgumentNullException for bad arguments, InvalidOperationException for calls made in the wrong state, NotSupportedException, TimeoutException. Don't write InvalidCustomerIdException.
  • Don't throw AppException subclasses for programming errors. A null that should never be null is a bug, and it should surface as a 500 with a stack trace.
  • Validation failures with several field errors are better modeled as a validation result than as an exception. Chapter 8 covers that.
  • The old pattern of adding a serialization constructor and [Serializable] is obsolete in .NET 8 (warning SYSLIB0051). Binary serialization of exceptions is no longer a goal, so leave them out in new code.

On .NET Framework

On .NET Framework, exceptions that cross AppDomain or remoting boundaries still need [Serializable] and the (SerializationInfo, StreamingContext) constructor. If you share these classes between a 4.8 service and a modern app through a .NET Standard library, add them behind #if NETFRAMEWORK.