Skip to content

Lesson 35 of 45 · Failure and Validation

Exception Handling as Design

Intermediate•
lesson•
November 6, 2026•
~9 min read

"Something went wrong"

You're reading old code. You see this:

PHP
<?php declare(strict_types=1); namespace App\Http\Controllers; use App\Reservations\ReservationId; use App\Reservations\Reservations; use Illuminate\Http\JsonResponse; use Psr\Clock\ClockInterface; final class CancelReservationController { public function __construct( private Reservations $reservations, private ClockInterface $clock, ) {} public function __invoke(string $reservationId): JsonResponse { try { $reservation = $this->reservations->withId(new ReservationId($reservationId)); $reservation->cancel('guest request', $this->clock->now()); $this->reservations->save($reservation); } catch (\Exception $e) { return new JsonResponse(['error' => 'Something went wrong'], 500); } return new JsonResponse(['status' => 'ok']); } }

The code runs but doesn't work. The user gets "something went wrong" and a 500 status code. The log shows the stack trace. Nobody knows whether the failure was "the reservation does not exist", "the payment provider was down", "the reservation is already cancelled", or "a typo in the SQL". All four are caught by the same generic catch. All four end up in the same error.

This is what happens when exceptions are treated as an afterthought: a safety net to keep the application from crashing, not a part of the design.

Generic catches turn rich failure information into noise. Specific exceptions, designed deliberately, turn failure into information the system can act on.

Exceptions are part of the contract

A method's signature tells you what inputs it takes and what value it returns. The exceptions it can throw are equally part of the contract.

PHP
<?php declare(strict_types=1); namespace App\Reservations; use DateTimeImmutable; interface CancelsReservations { public function cancel(ReservationId $id, DateTimeImmutable $now): void; }

What can go wrong here? In a well-designed system, the answer is enumerable:

  • The reservation might not exist (ReservationNotFound, a domain exception this lesson names but does not show).

  • The reservation might not be confirmed, which covers a reservation that is already cancelled (ReservationNotConfirmed, what Reservation::cancel() throws).

The cancel() method on Reservation earlier in this course threw CannotCancelReservation, which is another exception of this kind. Each failure mode is its own exception class, and each tells the caller (and any error handler) exactly what happened.

The signature is incomplete unless you can describe what kinds of failures the method emits. PHP doesn't enforce checked exceptions, and you don't need to document every exception a method might throw. But a method's failure modes should still be deliberate and locatable.

Three categories of failure

Different kinds of things go wrong. A useful three-category split:

Domain failures. A business rule is being violated. "You can't cancel a reservation that's already cancelled." "You can't withdraw more than your balance." "You can't reserve a room that is already booked for that slot." These aren't bugs; they're legitimate states the system has to communicate. They have names. They have specific HTTP status codes (usually 422 or 409). The caller often wants to do something specific in response.

Programming errors. Something the code expected to be impossible turned out to be possible. A null where the type system said no. A DivisionByZeroError from a divisor that was supposed to be positive. A method called on the wrong kind of object. These are bugs. They shouldn't happen in correct code. When they do, they should propagate, get logged, reach your error tracker, and fail the request so the bug gets fixed.

Infrastructure failures. External systems failed. The database is down. The third-party API timed out. The disk is full. Different from both domain and programming errors because the cause is outside the application's control. Often retriable. Often something the user can be told to try again.

These three call for different responses. Domain failures get translated to user-friendly messages with specific status codes. Programming errors get logged, reported, and fixed. Infrastructure failures get retried, fall back to degraded behavior, or surface as "we're having trouble, try again".

The next lesson shows where framework and vendor failures get translated into domain ones, and where domain failures become HTTP responses.

Throw early, catch late

A useful rule for where exceptions live in the call stack. Whichever way a failure is expressed, an exception or a result object (a later lesson covers when a result fits better), use the same way for similar failures across the codebase, not a mix of exceptions, null, false and result objects:

  • Throw as soon as the failure is recognized. When the rule is violated, when the precondition fails, when the impossible state is detected. Don't pass bad data forward. Don't return null from one layer and let the next layer rediscover the problem.

  • Catch as late as you can do something useful. Most code shouldn't catch at all. Let exceptions propagate up through the layers until they reach a place that knows what to do with them: an HTTP error handler that maps them to status codes, a queue worker that decides whether to retry, a top-level command runner that prints them to stderr.

Don't catch what you can't handle

In the codebases I've worked on, the most common error-handling mistake is the catch-everything block:

PHP
<?php declare(strict_types=1); namespace App\Reservations; final class WorkRunner { public function run(): void { try { $this->doWork(); } catch (\Throwable $e) { // log and ignore } } private function doWork(): void { // ... } }

This is error suppression, the opposite of error handling. The system pretends nothing happened. Bugs hide. Domain rules get violated silently. Infrastructure failures get masked. The team finds out when the data is corrupt.

The rule: catch only the specific exception types you know how to respond to. This queued job from the cancellation flow runs the CancelReservationCommandHandler and responds to exactly one failure:

PHP
<?php declare(strict_types=1); namespace App\Reservations\Jobs; use App\Reservations\CancelReservationCommand; use App\Reservations\CancelReservationCommandHandler; use App\Reservations\Exceptions\ReservationNotConfirmed; use App\Reservations\Exceptions\ReservationNotFound; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Queue\Queueable; use Illuminate\Queue\Middleware\FailOnException; final class CancelReservationJob implements ShouldQueue { use Queueable; public int $tries = 3; public int $backoff = 30; public function __construct(private readonly CancelReservationCommand $command) {} /** @return array<int, object> */ public function middleware(): array { return [new FailOnException([ReservationNotConfirmed::class])]; } public function handle(CancelReservationCommandHandler $handler): void { try { $handler->handle($this->command); } catch (ReservationNotFound) { // Nothing left to cancel: the booking was deleted after this job was queued. return; } } }

Returning on ReservationNotFound is a deliberate idempotency choice for this caller. A job that outlives its reservation, because an admin deleted a test booking while the job waited in the queue, has nothing left to do, and failing it would only fill the failed-jobs table. A controller that gets ReservationNotFound has a different answer (a 404, which the next lesson sets up), so the choice belongs to the caller, not to the exception.

Everything else propagates. ReservationNotConfirmed is a domain failure nobody can fix by retrying. Without help, the worker would run it three times before giving up, so the job's middleware() lists it in FailOnException, which calls fail() on the job when that exception comes out of handle(). The job lands in the failed-jobs list on the first attempt. A database outage is the infrastructure case. When withId() runs its query while the database is down, Eloquent throws Illuminate\Database\QueryException, which wraps the original PDOException. It is not a DomainException, and nothing has changed yet, so a retry is safe.

The job does not catch it. The worker sees the uncaught exception, releases the job after $backoff seconds and runs it again, up to $tries attempts. One job, three outcomes: ignore the failure that means "done", fail on the domain failure, retry on the infrastructure one.

In Symfony, Messenger retries a failed message according to the retry strategy configured on its transport. Throwing UnrecoverableMessageHandlingException stops the retries for that message, and RecoverableMessageHandlingException forces another one.

If you don't know what to do with \Throwable, don't catch it. Letting it propagate is the right move; the framework's top-level handler will turn it into a 500 response and report it to your log and error tracker.

Named exceptions tell stories

A specific exception class is worth more than a generic one with a message string. Compare throw new \Exception('Reservation not confirmed'); with the named version, thrown from Reservation::cancel() (trimmed to the fields this lesson needs):

PHP
<?php declare(strict_types=1); namespace App\Reservations; use App\Billing\Currency; use App\Billing\Money; use App\Reservations\Exceptions\ReservationNotConfirmed; use DateTimeImmutable; use Illuminate\Database\Eloquent\Model; final class Reservation extends Model { private const FREE_CANCELLATION_HOURS = 48; protected $casts = [ 'status' => ReservationStatus::class, 'check_in' => 'immutable_date', 'check_out' => 'immutable_date', 'cancelled_at' => 'immutable_datetime', ]; public function cancel(string $reason, DateTimeImmutable $now): Money { if ($this->status !== ReservationStatus::Confirmed) { throw new ReservationNotConfirmed(new ReservationId($this->id), $this->status); } $refundAmount = $this->refundAt($now); $this->status = ReservationStatus::Cancelled; $this->cancelled_at = $now; $this->cancellation_reason = $reason; return $refundAmount; } private function refundAt(DateTimeImmutable $now): Money { $currency = new Currency($this->currency); $freeUntil = $this->check_in->subHours(self::FREE_CANCELLATION_HOURS); if ($now < $freeUntil) { return Money::fromCents($this->total_price_cents, $currency); } return Money::zero($currency); } }

The named version gives you:

  • A type to catch specifically. catch (ReservationNotConfirmed $e) is precise.

  • Strong typing on the data the exception carries. $e->reservationId, $e->currentStatus, with proper types, no string parsing.

  • A name that shows up in stack traces, logs, and error tracking.

  • Documentation. The class itself is the documentation of the failure mode. A reader can grep for "throws ReservationNotConfirmed" or "catch (ReservationNotConfirmed" and find every relevant location.

Named exceptions like this usually share a common ancestor. A project-specific base class that every domain exception extends is useful:

PHP
<?php declare(strict_types=1); namespace App\Framework\Exceptions; abstract class DomainException extends \RuntimeException { // Common properties or methods, if any }

This is the app's own class, unrelated to PHP's built-in \DomainException, which extends \LogicException.

That gives you a shared type to catch when you want "any domain failure" and not "any failure at all" (catch (DomainException $e)), and a clear line between a business failure and a framework or runtime one.

PHP exception classes are cheap to write:

PHP
<?php declare(strict_types=1); namespace App\Reservations\Exceptions; use App\Framework\Exceptions\DomainException; use App\Reservations\ReservationId; use App\Reservations\ReservationStatus; final class ReservationNotConfirmed extends DomainException { public function __construct( public readonly ReservationId $reservationId, public readonly ReservationStatus $currentStatus, ) { parent::__construct( "Reservation {$reservationId->value} is not confirmed (status: {$currentStatus->value})" ); } }

Throwing it costs nothing extra over throwing a generic exception, and catching it specifically is more useful than catching \Exception.

PHP-specific notes

A few practical points:

Throwable vs Exception vs Error. PHP 7+ has \Throwable as the root of the catchable hierarchy, with \Exception and \Error as the two main branches. \Error covers engine-level failures such as TypeError and DivisionByZeroError. \Exception covers the rest, including LogicException subclasses such as InvalidArgumentException, which signal programming errors. Catching \Exception doesn't catch \Error. Catching \Throwable catches both. In application code, catch specific subclasses.

$previous. The next lesson covers passing the original exception when you wrap one.

Keep exceptions cheap to construct. Rich exception classes with file IO, database lookups, or external calls in their constructors are an anti-pattern. The exception is being thrown because something went wrong; making the throw itself slow or fragile compounds the problem.

Pitfalls

A few common mistakes:

Using exceptions for control flow. Exceptions are for exceptional cases, not for "find the first item that matches". A method that throws to signal "no match found" and is routinely called in a loop is performing a flow-control hack. Return a result object, or an empty collection.

Catching just to re-throw. catch (\Exception $e) { throw $e; } does nothing. If you have nothing to add, don't catch.

Stack of try-catches at every layer. Each layer catches, wraps, and rethrows. The original error gets buried under five wrappers. Stack traces become unreadable.

The one thing to remember

When you write a method, think about what can go wrong as part of writing the signature. The kinds of failure are part of the contract. Name the kinds of failure a method can produce and throw them deliberately. Catch one only where you can do something specific about it.

Course Content