Skip to content

Lesson 36 of 45 · Failure and Validation

Domain Exceptions vs Framework Exceptions

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

The exception that broke the abstraction

You build a clean handler, a domain model and a repository, and wire them together. Then you read this handler, written against a repository whose withId() calls findOrFail():

PHP
<?php declare(strict_types=1); namespace App\Reservations; use App\Reservations\Exceptions\ReservationNotFound; use Illuminate\Database\Eloquent\ModelNotFoundException; use Psr\Clock\ClockInterface; final readonly class CancelReservationCommandHandler { public function __construct( private Reservations $reservations, private ClockInterface $clock, ) {} public function handle(CancelReservationCommand $command): void { try { $reservation = $this->reservations->withId($command->reservationId); } catch (ModelNotFoundException $e) { throw new ReservationNotFound($command->reservationId, $e); } $reservation->cancel($command->reason, $this->clock->now()); $this->reservations->save($reservation); } }

The ModelNotFoundException import is the giveaway. The handler had to know about Eloquent's specific exception type. Framework decoupling just got broken in one line. The repository was supposed to hide persistence; the exception leaked through.

There's a line between exceptions that are part of your domain and exceptions that come from the framework or runtime, and mixing them couples business code to the framework. A ModelNotFoundException also says only that a row was missing. It doesn't say which reservation, or why it was looked up, and that is the information the domain needs.

Domain exceptions and framework exceptions

A domain exception is a named failure that belongs to your business: ReservationNotFound, ReservationNotConfirmed, OutsideFreeCancellationWindow, PaymentNotFound. It carries the data the business cares about (the reservation id, the payment id), usually maps to one user-visible response, and lives in business code where handlers, models and repositories can throw and catch it.

A framework exception is a failure that belongs to the framework or the runtime: \Illuminate\Database\Eloquent\ModelNotFoundException, \Illuminate\Validation\ValidationException, \Illuminate\Auth\AuthenticationException, \PDOException. It tells the framework what happened so it can return a 404, return a 422 or retry the query. It does not express a business failure.

The translation pattern

Framework exceptions get caught in infrastructure code, where the framework lives, and translated into domain exceptions before they cross into business code.

The Reservations repository is the canonical place for this. Its EloquentReservations::withId() calls find(), checks for null, and throws ReservationNotFound instead of using findOrFail() and catching ModelNotFoundException. The handler that calls it never sees an Eloquent exception, only domain exceptions that mean something in the business. ReservationNotFound takes the id and an optional previous exception. It extends DomainException like ReservationNotConfirmed in the previous lesson. Earlier lessons in this course call it with the id only, which the optional second argument allows:

PHP
<?php declare(strict_types=1); namespace App\Reservations\Exceptions; use App\Framework\Exceptions\DomainException; use App\Reservations\ReservationId; use Throwable; final class ReservationNotFound extends DomainException { public function __construct(public readonly ReservationId $reservationId, ?Throwable $previous = null) { parent::__construct("Reservation {$reservationId->value} was not found", previous: $previous); } }

Some libraries have no "return null" alternative. For those the same pattern applies, with explicit translation inside the adapter that wraps the library. StripePayments is that adapter. Stripe's PHP library throws Stripe\Exception\InvalidRequestException for a payment intent that doesn't exist, and getStripeCode() returns resource_missing for it. Only capture() changes from the earlier version:

PHP
<?php declare(strict_types=1); namespace App\Payments; use App\Billing\Money; use App\Payments\Exceptions\PaymentNotFound; use App\Reservations\ReservationId; use Stripe\Exception\InvalidRequestException; use Stripe\StripeClient; final readonly class StripePayments implements Payments { public function __construct(private StripeClient $stripe) {} public function authorize(ReservationId $id, Money $amount): PaymentAuthorization { $intent = $this->stripe->paymentIntents->create([ 'amount' => $amount->amountInCents, 'currency' => strtolower($amount->currency->isoCode), 'capture_method' => 'manual', 'metadata' => ['reservation_id' => $id->value], ]); return new PaymentAuthorization(new PaymentId($intent->id)); } public function capture(PaymentId $id): PaymentCapture { try { $this->stripe->paymentIntents->capture($id->value, []); } catch (InvalidRequestException $e) { if ($e->getStripeCode() !== 'resource_missing') { throw $e; } throw new PaymentNotFound($id, $e); } return new PaymentCapture($id); } public function refund(PaymentId $id, Money $amount): PaymentRefund { $this->stripe->refunds->create([ 'payment_intent' => $id->value, 'amount' => $amount->amountInCents, ]); return new PaymentRefund($id, $amount); } }

Only the missing-intent error becomes a domain exception, and any other InvalidRequestException is rethrown unchanged. PaymentNotFound names a concept the business recognizes, and it extends the DomainException base class from the previous lesson, which gives the mapping below a type to catch for "any domain failure":

PHP
<?php declare(strict_types=1); namespace App\Payments\Exceptions; use App\Framework\Exceptions\DomainException; use App\Payments\PaymentId; use Throwable; final class PaymentNotFound extends DomainException { public function __construct(public readonly PaymentId $paymentId, ?Throwable $previous = null) { parent::__construct("Payment {$paymentId->value} was not found", previous: $previous); } }

Stripe's AuthenticationException and RateLimitException propagate untouched. RateLimitException extends InvalidRequestException, which is why the catch checks the code before translating. They are infrastructure failures, the third category from the previous lesson, and translating them into a DomainException would make the bootstrap/app.php mapping below report them to the client as 422s. The previous argument keeps the original error for debugging.

The same translation for a database constraint

The unique: validation rule in a form request checks the table before the insert, so two simultaneous registrations with the same email can both pass it. The unique index on email is the real guard, and the database reports the loser as an Illuminate\Database\UniqueConstraintViolationException. EloquentGuests implements Guests, which combines the ReadsGuests and WritesGuests interfaces from the SOLID lesson and is the interface a later lesson fakes. It translates that exception where the insert happens. GuestModel is the Eloquent model for guests, and toGuest() is a method on it that rebuilds a Guest and isn't shown. The interface and the missing-guest exception come first:

PHP
<?php declare(strict_types=1); namespace App\Booking; interface Guests extends ReadsGuests, WritesGuests {}
PHP
<?php declare(strict_types=1); namespace App\Booking\Exceptions; use App\Booking\GuestId; use App\Framework\Exceptions\DomainException; use Throwable; final class GuestNotFound extends DomainException { public function __construct(public readonly GuestId $guestId, ?Throwable $previous = null) { parent::__construct("Guest {$guestId->value} was not found", previous: $previous); } }

Now the repository:

PHP
<?php declare(strict_types=1); namespace App\Booking; use App\Booking\Exceptions\DuplicateGuestEmail; use App\Booking\Exceptions\GuestNotFound; use App\Booking\Models\GuestModel; use Illuminate\Database\UniqueConstraintViolationException; final readonly class EloquentGuests implements Guests { public function withId(GuestId $id): Guest { $row = GuestModel::query()->find($id->value); return $row?->toGuest() ?? throw new GuestNotFound($id); } public function withEmail(EmailAddress $email): ?Guest { return GuestModel::query()->where('email', $email->value)->first()?->toGuest(); } public function save(Guest $guest): void { $row = GuestModel::query()->find($guest->id->value) ?? new GuestModel(); $row->forceFill([ 'id' => $guest->id->value, 'email' => $guest->email->value, 'name' => $guest->name, ]); try { $row->save(); } catch (UniqueConstraintViolationException $e) { throw new DuplicateGuestEmail($guest->email, $e); } } }

The block writes only the columns this lesson needs. The guests table's only unique index besides the primary key is email, which is why the catch can name the failure DuplicateGuestEmail. The exception carries the address that collided:

PHP
<?php declare(strict_types=1); namespace App\Booking\Exceptions; use App\Booking\EmailAddress; use App\Framework\Exceptions\DomainException; use Throwable; final class DuplicateGuestEmail extends DomainException { public function __construct(public readonly EmailAddress $email, ?Throwable $previous = null) { parent::__construct("A guest with email {$email->value} already exists", previous: $previous); } }

The registration handler in the next lesson catches DuplicateGuestEmail and returns a result instead of letting it escape. On Symfony, an earlier lesson already shows the Doctrine DBAL UniqueConstraintViolationException caught in a listener.

Turning domain exceptions into HTTP responses

Laravel lets an exception define its own render() method that returns an HTTP response. Putting that on a domain exception means importing Illuminate\Http\Request and JsonResponse into it, which is the leak this lesson is about. Keep the exceptions free of HTTP and register the mapping in bootstrap/app.php with withExceptions:

PHP
<?php declare(strict_types=1); use App\Framework\Exceptions\DomainException; use App\Reservations\Exceptions\ReservationNotFound; use Illuminate\Foundation\Application; use Illuminate\Foundation\Configuration\Exceptions; use Illuminate\Foundation\Configuration\Middleware; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; return Application::configure(basePath: dirname(__DIR__)) ->withRouting( web: __DIR__.'/../routes/web.php', commands: __DIR__.'/../routes/console.php', health: '/up', ) ->withMiddleware(function (Middleware $middleware): void { // }) ->withExceptions(function (Exceptions $exceptions): void { $exceptions->shouldRenderJsonWhen( fn (Request $request) => $request->is('api/*') || $request->expectsJson(), ); $exceptions->render(function (ReservationNotFound $e, Request $request) { return new JsonResponse(['error' => 'reservation_not_found'], 404); }); $exceptions->render(function (DomainException $e, Request $request) { return new JsonResponse([ 'error' => 'domain_rule_violated', 'message' => $e->getMessage(), ], 422); }); })->create();

The shouldRenderJsonWhen call is the one the Laravel 13.x skeleton ships with. Laravel picks the callback by the type hint on its first parameter, and the callbacks are tried in the order you register them, so the specific ReservationNotFound goes before the general DomainException. Controllers stay free of error-translation logic, and the HTTP status for each failure lives in one file.

A feature test proves the mapping. It swaps the repository for InMemoryReservations (a later lesson builds it) and posts to the check-out route from earlier in the course for a reservation that doesn't exist:

PHP
<?php declare(strict_types=1); namespace Tests\Feature\Reservations; use App\Reservations\Reservations; use App\Testing\InMemoryReservations; use Tests\TestCase; final class ReservationNotFoundResponseTest extends TestCase { public function test_a_missing_reservation_is_a_404_with_a_json_error(): void { $this->instance(Reservations::class, new InMemoryReservations()); $response = $this->postJson('/reservations/missing-reservation/check-out'); $response->assertNotFound(); $response->assertExactJson(['error' => 'reservation_not_found']); } }

In Symfony, the same mapping is configuration. framework.exceptions takes an exception class and a status_code, so App\Reservations\Exceptions\ReservationNotFound: { status_code: 404 } under framework: in config/packages/framework.yaml keeps HTTP off the domain class. The first matching class in config order wins, so ReservationNotFound goes before App\Framework\Exceptions\DomainException, as with the Laravel callbacks. The #[WithHttpStatus] attribute does the same job but puts the status on the class. An exception from a handler on a synchronous Messenger bus arrives wrapped in HandlerFailedException. ErrorListener matches the configured classes against the thrown exception only, so a mapping on ReservationNotFound doesn't match the wrapper, and the code that dispatches the command has to unwrap it first.

When to translate

Translate at the boundary where a domain concept exists on the other side: a ModelNotFoundException becomes ReservationNotFound, a Stripe resource_missing becomes PaymentNotFound. The previous lesson covers when to catch at all. Leave the exception alone when it is a framework concern (ValidationException, routing errors, rate limiting) that the framework boundary handles directly, or a programming error such as \TypeError, which should propagate to be logged and fixed.

Pitfalls

Inheriting from framework exceptions. Making your domain exceptions extend \Illuminate\Database\Eloquent\ModelNotFoundException to "get integration for free" couples the domain exception to the framework. The opposite move (extending a project-specific DomainException that extends \RuntimeException) is cleaner.

Throwing generic built-in exceptions from domain code. A domain method that throws \InvalidArgumentException is using a PHP built-in, not a framework class, which is fine in a pinch but lacks domain meaning. Prefer a named domain exception (InvalidCouponCode). Value-object constructors that throw InvalidArgumentException, like EmailAddress, are the accepted exception to that rule.

The one thing to remember

If a domain handler's imports include anything from \Illuminate\Database, \Symfony\Component\HttpKernel, or any third-party SDK's exception namespace, the abstraction is leaking. The boundary where you turn framework exceptions into domain exceptions is usually the repository or the class that wraps the SDK. Move the translation there, and let the rest of the code speak in its own language.

Course Content