Designing Exceptions

7.Designing Exceptions

M

In this chapter

We'll learn where exceptions should be caught — exception boundaries at the edges of the application — the difference between domain and infrastructure exceptions and how to translate one into the other, how to tell recoverable failures from unrecoverable ones, when returning null is better than throwing, the anti-patterns to avoid, and how to document exceptions when PHP has no checked exceptions.

17–19 min

The Problem in Real Life

Marcus searches the code for catch and finds 31 of them. Eleven catch an exception, log it and throw it again, so one database timeout appears four times in the log. Six catch Throwable and return false. One catches Exception around the SMS sending and carries on — which is why three customers never got a reminder last week, and nobody knew.

Meanwhile the booking page catches PDOException directly, so the page knows which database driver the project uses.

M

Most of these catches shouldn't exist. The ones that should exist are in the wrong place.

Marcus

Catches Everywhere vs. Boundaries by Design

Catch at the edges

Code in the middle throws; the page, the command or the job at the edge decides what happens.

Two kinds of exception

Domain exceptions describe business rules; infrastructure exceptions describe broken machinery.

Can we recover?

Retry, fall back, ask the user — or stop and fix the bug. The design depends on the answer.

Designing Exceptions

Exceptions are part of the design: chapters 1–6 covered how exceptions work. This chapter is about which exceptions a project should have and where they should be handled. It covers:

  • Exception boundaries: where to catch.
  • Domain exceptions: business rules, in business words.
  • Infrastructure exceptions: wrapping the machinery.
  • Recovery: recoverable vs. unrecoverable failures.
  • Good habits: when not to throw, anti-patterns, and documenting exceptions.

Exception boundaries: an exception boundary is a place where an exception stops travelling and is turned into a result: a web page, a command's exit code, a retried job. Good boundaries are at the edges of the application — the code that handles a web request (the controller or front script), a terminal command, a queue job — plus the last-resort handler from chapter 5. Code in the middle — services, repositories, Money — mostly just throws and lets exceptions pass. A catch in the middle is right only when that code can really do something: translate the exception (below), retry, or clean up and rethrow. The diagram below shows BookBay's layers.

Where BookBay throws and where it catches

Boundary: booking page / SendReminders command / queue job

catches: shows a message, sets the status or exit code, logs once

calls

BookingService

throws SlotTakenException, ShopClosedException; lets others pass

calls

BookingRepository

catches PDOException → throws DatabaseUnavailableException (previous: $e)

SmsGateway

catches ConnectException → throws SmsUnavailableException

calls

PDO / database

throws PDOException

Guzzle / SMS API

throws ConnectException

Domain exceptions: a domain exception says that a business rule stopped the action: SlotTakenException, ShopClosedException, BookingNotFoundException. They're named in the language Olivia uses, they live with the business code (BookBay\Booking\…), and they're expected: the boundary catches them and shows a specific message — "please choose another time". They usually extend DomainException or RuntimeException, and a marker interface like BookingException groups them (chapter 3).

Infrastructure exceptions: an infrastructure exception says that some machinery failed: the database, the SMS provider, the disk. Low-level libraries throw their own types — PDOException, Guzzle's ConnectException — and if those travel all the way up, the booking page has to know about PDO and Guzzle. Instead, the code that talks to the machinery translates them at its own boundary: the repository catches PDOException and throws DatabaseUnavailableException with the original as previous. The rest of the project depends only on BookBay's own exception, and if the database library changes, only the repository changes. That's dependency inversion (Act 11) applied to failures.

Translating an infrastructure exception at the repository
<?php
final class DatabaseUnavailableException extends RuntimeException {}
final class BookingRepository
{
public function find(int $id): ?array
{
try {
return $this->query("SELECT * FROM bookings WHERE id = ?", [$id]);
} catch (PDOException $e) {
throw new DatabaseUnavailableException("Could not load booking {$id}", previous: $e);
}
}
private function query(string $sql, array $params): ?array
{
throw new PDOException("SQLSTATE[HY000] [2002] Connection refused"); // simulated outage
}
}
try {
(new BookingRepository())->find(4812);
} catch (DatabaseUnavailableException $e) { // the page knows nothing about PDO
echo $e->getMessage(), " <- ", $e->getPrevious()->getMessage(), "\n";
}
// Could not load booking 4812 <- SQLSTATE[HY000] [2002] Connection refused

Recoverable vs. unrecoverable failures: before deciding how to handle a failure, ask whether anything can make it succeed. A temporary failure — a timeout, a busy service — can be retried, a few times with a pause. A failure with an alternative can fall back: if the SMS fails, queue it and send an email. A failure the user can fix gets a clear message: the slot is taken, pick another. A bug — TypeError, ArgumentCountError, a LogicException — can't be recovered at all: retrying runs the same broken code. Let it reach the last-resort handler, log it loudly, and fix the code. The table below sorts the common cases.

Table — Recoverable or not?
FailureKindHandle byWhere
SMS API timeoutTemporaryRetry 3 times, then queue for laterSmsGateway / queue job
SMS provider down for hoursHas an alternativeFall back to emailReminder service
Slot already takenUser can fix itMessage: choose another timeBooking page
Database downInfrastructureFriendly 500 page, critical log, alertBoundary
TypeError, ArgumentCountErrorBugDon't catch: log loudly and fix the codeLast-resort handler
Retrying a temporary failure
<?php
final class SmsTimeoutException extends RuntimeException {}
function sendSms(string $to, int $attempt): void
{
if ($attempt < 3) {
throw new SmsTimeoutException("Timeout after 5s"); // fails twice, then works
}
echo "Sent to {$to} on attempt {$attempt}\n";
}
function sendWithRetry(string $to, int $maxAttempts = 3): void
{
for ($attempt = 1; ; $attempt++) {
try {
sendSms($to, $attempt);
return;
} catch (SmsTimeoutException $e) {
if ($attempt === $maxAttempts) {
throw $e; // give up: let the boundary decide
}
echo "attempt {$attempt} failed: ", $e->getMessage(), ", retrying\n";
// real code: usleep(200_000 * $attempt);
}
}
}
sendWithRetry("+447700900456");
// attempt 1 failed: Timeout after 5s, retrying
// attempt 2 failed: Timeout after 5s, retrying
// Sent to +447700900456 on attempt 3

When not to throw: exceptions are for situations where a function can't do its job. When "nothing found" is a normal answer, return it: find(int $id): ?Booking returns null, and the caller decides. A second method can throw for callers who need a booking: findOrFail(), which throws BookingNotFoundException — Laravel uses exactly these two names. Form validation is another case: a form with three wrong fields should report all three, so validation returns a list of errors (Act 17) instead of throwing at the first one. And never use exceptions as a normal if — they're slower and hide the flow.

find() returns null; findOrFail() throws
<?php
final class BookingNotFoundException extends RuntimeException
{
public static function forId(int $id): self
{
return new self("Booking {$id} does not exist");
}
}
final class Bookings
{
private array $rows = [4811 => "Tom Hart"];
public function find(int $id): ?string
{
return $this->rows[$id] ?? null; // "not found" is a normal answer
}
/** @throws BookingNotFoundException */
public function findOrFail(int $id): string
{
return $this->find($id) ?? throw BookingNotFoundException::forId($id);
}
}
$bookings = new Bookings();
echo $bookings->find(4812) ?? "no booking: show the search form", "\n";
try {
$bookings->findOrFail(4812);
} catch (BookingNotFoundException $e) {
echo $e->getMessage(), "\n";
}
// no booking: show the search form
// Booking 4812 does not exist

Anti-patterns: Marcus's 31 catches contain all the classic mistakes. Swallowing — an empty catch, or one that returns false — loses the failure. Catching everything in the middle — catch (Throwable) in a service — hides bugs that should crash loudly. Log-and-rethrow at every layer writes the same failure many times; log once, at the boundary. Losing the cause — throwing a new exception without previous. Leaking technical messages to users, like showing a PDOException's message on the page. And catching too early, in code that can't do anything useful about it. The second table lists the fixes.

Table — Anti-patterns and their fixes
Anti-patternLooks likeFix
Swallowingcatch (Exception $e) {} or return falseLet it propagate, or handle it for real
Catching too broadlycatch (Throwable) in a serviceCatch specific types; Throwable only at the last-resort boundary
Log and rethrow everywherelog, throw $e; in every layerLog once, at the boundary
Losing the causethrow new X("failed")throw new X("failed", previous: $e)
Leaking detailsecho $e->getMessage() to customersUser text chosen at the boundary; details to the log
Exceptions as if/elsethrow to leave a loopReturn values and normal control flow

Documenting exceptions: PHP has no checked exceptions (chapter 1), so a function's signature doesn't say what it can throw. Write it in a @throws tag above the function — @throws SlotTakenException — for the exceptions callers are expected to handle; static analysers like PHPStan (Act 21) can check that they're caught or passed on. Some languages make failure part of the return type instead: Rust's Result<Booking, BookingError> and Go's (Booking, error) force the caller to look. PHP doesn't support a built-in Result type; a few libraries add one, but most PHP code — and every framework — uses exceptions plus @throws.

Rust: failure in the return type (PHP has no Result type)
// Rust — the caller must handle both cases
fn find_or_fail(id: u32) -> Result<Booking, BookingError> {
repository.find(id).ok_or(BookingError::NotFound(id))
}
match find_or_fail(4812) {
Ok(booking) => show(booking),
Err(BookingError::NotFound(id)) => not_found_page(id),
}

Key Takeaway

Catch exceptions at boundaries — the request handler, command, queue job and the last-resort handler — and let code in the middle throw; catch in the middle only to translate, retry or clean up. Domain exceptions name broken business rules and get specific user messages; infrastructure exceptions wrap low-level ones (PDOException → DatabaseUnavailableException with previous) so the rest of the code doesn't depend on the machinery. Retry temporary failures, fall back where there's an alternative, explain user-fixable ones, and let bugs crash loudly. Return null for normal "not found" (find vs findOrFail), collect validation errors, avoid swallowing, broad catches and repeated logging, and document expected exceptions with @throws.

Why This Matters

Exception design decides whether failures are handled in one predictable place or scattered across hundreds of catches. Laravel's architecture follows it exactly: services throw, the exception handler at the edge renders and reports.

The domain-vs-infrastructure split is also the first step towards the layered architecture of Act 22: business code that doesn't know which database or SMS provider it runs on is easier to test, change and understand.

Of the 31 catches, nine remain: one boundary per entry point, two translations in the repository and the SMS gateway, one retry, and the last-resort handlers. The reminder failures now reach the log as SmsUnavailableException with their cause, and fall back to email. Time to design it all yourself, in the Errors Checkpoint.