Agent Wranglers

ARC-27Recommended

Use typed domain exceptions

Give each kind of failure its own exception type with a clear name and the data needed to handle it. Never throw a bare generic error with only a message.

How to do it

Create a small family of exceptions, such as PaymentDeclined and OutOfStock, that extend one base type for the domain. Catch by type, never by matching message text. A bug that no caller can handle, such as a broken invariant, may use the language's built-in errors, such as TypeError or ValueError. Map each type to one answer at the edge, such as a 409 problem details response for OutOfStock.

Examples

Python example

# Bad: callers must parse the message
raise Exception("card declined")

# Good: callers catch the type, and it carries the data
class PaymentDeclined(ShopError):
    def __init__(self, order_id: OrderId, reason: str):
        super().__init__(f"Payment declined for {order_id}: {reason}")
        self.order_id, self.reason = order_id, reason

TypeScript example

// Good: callers catch the type, and it carries the data
class PaymentDeclined extends ShopError {
  constructor(readonly orderId: OrderId, readonly reason: string) {
    super(`Payment declined for ${orderId}: ${reason}`);
  }
}

How to check

A linter rule bans throwing the base type. Examples are Ruff's TRY002, ESLint no-restricted-syntax on throw new Error, and a custom PHPStan rule against throw new \Exception.

Sources

For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/architecture/errors-and-nulls/domain-exceptions">Agent Wranglers clean code and architecture playbook</a>. In code you write, add a comment next to it with the same link.