Lesson 37 of 45 · Failure and Validation
The Result Pattern: An Alternative to Throwing Exceptions
When throwing isn't quite right
A handler tries to register a new guest and the email is already in use. The previous lesson said to throw a domain exception, let it propagate and render it at the boundary, which is clean for the controller but awkward for the handler's caller.
The caller in this case is a "register or sign in" use case. If the email is taken, the right move is to email a sign-in link to that address and answer the request normally, without logging anyone in. A taken email is a routine outcome the caller wants to handle inline, and throwing is a heavier mechanism than that wants. It fits "the database is on fire" or "the guest doesn't exist when we expected them to".
The alternative is a result object: a return value that explicitly represents "either success with this data, or failure with this reason". The caller sees both outcomes in the return type.
What a result object is
The caller can't read the success data without first checking which state it got, because the return type is the wrapper, not the data. Both branches have to be considered.
In Rust this is Result<T, E>, and the compiler warns when you ignore one. In PHP, we approximate it.
A PHP shape: one class per outcome
PHP has no sum types, so the shape is an abstract base class with one final class per outcome. The base class is the operation's return type, and each outcome carries its own typed data. Here is the base class for registering a guest, and its three outcomes:
<?php
declare(strict_types=1);
namespace App\Booking\Results;
abstract readonly class RegisterGuestResult {}<?php
declare(strict_types=1);
namespace App\Booking\Results;
use App\Booking\Guest;
final readonly class RegistrationSucceeded extends RegisterGuestResult
{
public function __construct(public Guest $guest) {}
}<?php
declare(strict_types=1);
namespace App\Booking\Results;
use App\Booking\EmailAddress;
final readonly class EmailAlreadyInUse extends RegisterGuestResult
{
public function __construct(public EmailAddress $email) {}
}<?php
declare(strict_types=1);
namespace App\Booking\Results;
final readonly class WeakPassword extends RegisterGuestResult
{
/** @param list<string> $rulesViolated */
public function __construct(public array $rulesViolated) {}
}Each variant has its own class with its own data, and the union of them is the operation's possible outcomes. Adding a new variant means adding a new class.
A worked example
The handler works with a few small classes. RegisterGuestCommand is the command from earlier in the course (email and name) with a password added, all raw strings from the request. Guest is trimmed to what this lesson needs, so the name guard that the next lesson shows is left out:
<?php
declare(strict_types=1);
namespace App\Booking;
final readonly class RegisterGuestCommand
{
public function __construct(
public string $email,
public string $name,
public string $password,
) {}
}<?php
declare(strict_types=1);
namespace App\Booking;
use DateTimeImmutable;
final class Guest
{
private function __construct(
public readonly GuestId $id,
public readonly EmailAddress $email,
public readonly string $name,
private string $passwordHash,
private DateTimeImmutable $registeredAt,
) {}
public static function register(
EmailAddress $email,
string $name,
string $passwordHash,
DateTimeImmutable $registeredAt,
): self {
return new self(GuestId::next(), $email, $name, $passwordHash, $registeredAt);
}
}Guests is the repository interface from the previous lesson, with withId(), withEmail() and save(). A later lesson builds an in-memory fake of it. GuestRegistered (namespace App\Booking\Events) is an event that carries a GuestId. PasswordPolicy has two static methods, isStrong() and violations(), and their bodies don't matter here. The handler depends on the course's own EventDispatcher interface and returns a result instead of throwing:
<?php
declare(strict_types=1);
namespace App\Booking;
use App\Booking\Events\GuestRegistered;
use App\Booking\Exceptions\DuplicateGuestEmail;
use App\Booking\Results\EmailAlreadyInUse;
use App\Booking\Results\RegisterGuestResult;
use App\Booking\Results\RegistrationSucceeded;
use App\Booking\Results\WeakPassword;
use App\Framework\Events\EventDispatcher;
use Illuminate\Contracts\Hashing\Hasher;
use Psr\Clock\ClockInterface as Clock;
final readonly class RegisterGuestCommandHandler
{
public function __construct(
private Guests $guests,
private Hasher $hasher,
private Clock $clock,
private EventDispatcher $events,
) {}
public function handle(RegisterGuestCommand $command): RegisterGuestResult
{
$email = new EmailAddress($command->email);
if (!PasswordPolicy::isStrong($command->password)) {
return new WeakPassword(PasswordPolicy::violations($command->password));
}
if ($this->guests->withEmail($email) !== null) {
return new EmailAlreadyInUse($email);
}
$guest = Guest::register(
email: $email,
name: $command->name,
passwordHash: $this->hasher->make($command->password),
registeredAt: $this->clock->now(),
);
try {
$this->guests->save($guest);
} catch (DuplicateGuestEmail) {
return new EmailAlreadyInUse($email);
}
$this->events->dispatch(new GuestRegistered($guest->id));
return new RegistrationSucceeded($guest);
}
}The withEmail() check is the early answer, and the try/catch covers two registrations for the same email that both pass it before either saves. The previous lesson shows the repository turning the unique-index violation into DuplicateGuestEmail. The event is dispatched after the try/catch, so the loser of the race never announces a guest that was not saved.
This handler breaks the void rule from command-query separation on purpose, because the caller needs to know which of three things happened. The cost is that it can't be queued, since nothing is waiting for a return value from a worker. The course's CommandBus::dispatch() returns void, so the controller holds the handler directly. Laravel's dispatchNow() and Symfony's HandleTrait::handle() (which reads the HandledStamp) would pass the value back, and the Command Bus lesson explains why its bus doesn't.
The Hasher is Laravel's. In Symfony, inject Symfony\Component\PasswordHasher\PasswordHasherInterface and call $this->hasher->hash($command->password).
The caller has to decide what to do with every branch. Sending the sign-in link goes through a small interface, so the controller doesn't care how the email is delivered:
<?php
declare(strict_types=1);
namespace App\Booking;
interface SignInLinks
{
public function sendTo(EmailAddress $email): void;
}<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Booking\RegisterGuestCommand;
use App\Booking\RegisterGuestCommandHandler;
use App\Booking\Results\EmailAlreadyInUse;
use App\Booking\Results\RegistrationSucceeded;
use App\Booking\Results\WeakPassword;
use App\Booking\SignInLinks;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
final class RegisterGuestController
{
public function __construct(
private RegisterGuestCommandHandler $registerGuest,
private SignInLinks $signInLinks,
) {}
public function __invoke(Request $request): JsonResponse
{
$result = $this->registerGuest->handle(new RegisterGuestCommand(
email: $request->string('email')->toString(),
name: $request->string('name')->toString(),
password: $request->string('password')->toString(),
));
return match (true) {
$result instanceof RegistrationSucceeded => $this->checkYourEmail(),
$result instanceof EmailAlreadyInUse => $this->sendSignInLink($result),
$result instanceof WeakPassword => new JsonResponse([
'error' => 'weak_password',
'rules_violated' => $result->rulesViolated,
], 422),
};
}
private function sendSignInLink(EmailAlreadyInUse $result): JsonResponse
{
$this->signInLinks->sendTo($result->email);
return $this->checkYourEmail();
}
private function checkYourEmail(): JsonResponse
{
return new JsonResponse(['message' => 'Check your email.'], 202);
}
}Both outcomes return the same 202 and the same message. If a new registration answered 201 and a taken email answered 202, anyone could learn which addresses have accounts by submitting them. The weak-password check runs before the email lookup for the same reason: otherwise a 422 would also mean "this email is new". The sign-in link has to be single-use and expiring, and the endpoint rate-limited, or it becomes a way to flood someone's inbox. Response time can also differ between the two paths, because a new guest's password gets hashed and a taken email triggers a mail send, so queue the work that differs if timing matters to you.
A malformed email still makes new EmailAddress throw InvalidArgumentException, so a real controller would sit behind the form request from the next lesson, which rejects those before the handler runs.
What the match does when a variant is missing
The match (true) has no default arm, and that is deliberate. A new outcome, such as one for a guest whose email domain is blocked, is one more class:
<?php
declare(strict_types=1);
namespace App\Booking\Results;
final readonly class RegistrationBlocked extends RegisterGuestResult
{
public function __construct(public string $reason) {}
}Suppose the handler gets one more return, return new RegistrationBlocked('blocked email domain');, and nobody updates the controller's match. A request that reaches it makes PHP throw UnhandledMatchError with the message "Unhandled match case true", which echoes the match (true) subject rather than naming the variant. Nothing catches it, so the client gets a 500 instead of a wrong response. PHP checks this at runtime only, so a request or test that returns each variant is what finds it before production.
When result objects beat exceptions
The pattern earns its place when:
The "failure" is a routine business outcome. Email already in use. Coupon expired. Inventory unavailable. These are everyday cases the caller should reasonably handle inline. Throwing for them mixes flow control into the exception system.
The caller wants to handle both branches differently. The result type makes the caller look at the outcome. With exceptions, "I forgot to catch" is a real risk.
There are several distinct failure shapes the caller cares about.
matchover the variants is cleaner than four nested catches.Failure modes carry rich, typed data. Exceptions can carry data, but the structure is less obvious than a typed variant class.
EmailAlreadyInUse $rwith$r->emailis more honest than catching an exception and reading its properties.
When exceptions still beat result objects
Some situations are still better as exceptions:
Truly exceptional cases. "Database is down." "Disk is full." "Programming error." These rarely have a meaningful "handle both branches" response. Let them propagate.
Failures the caller almost never handles. If nearly every caller would just rethrow the result, you've made them write boilerplate for nothing. Throw and let the framework handle it.
Cases where the caller is multiple levels removed. Exceptions naturally bubble through layers. Result objects have to be passed through each intermediate caller, which adds verbosity.
Already-thrown framework exceptions. Wrapping them all in result objects is rarely worth it. Translation at the boundary keeps them as exceptions in your code; result objects would just add another layer.
Most operations use both. In the worked example the handler returns a RegisterGuestResult for the outcomes the caller handles, and a database failure mid-save is still an exception that propagates to the framework. A codebase where everything is a result still has to catch what the framework and drivers throw, and a codebase where everything throws loses the type safety around routine failures. On a synchronous Symfony Messenger bus, a handler's exception arrives wrapped in HandlerFailedException, which the Command Bus lesson covers.
Libraries vs hand-rolled
Libraries such as prewk/result provide a Rust-inspired Result<T, E> for PHP, with ready-made methods for transforming and unwrapping values that hand-rolled types usually don't have. They're useful in codebases that lean heavily into the pattern.
I'd start with hand-rolled domain-specific result classes (like the RegisterGuestResult example above). They're typed, named after the domain, and don't introduce a generic abstraction the team has to learn. The cost is one base class per use case.
Pitfalls
Result objects everywhere, even for things that should throw. A Result returned from Guests::withId(GuestId $id) ("found guest or not") is bad design when the caller almost always expects the guest to exist. Throw GuestNotFound, the domain exception from the previous lesson, and reserve results for cases the caller really wants to handle inline.
Untyped success data. A result that carries mixed gives you no type safety, so the typed variant classes above are the fix.
The one thing to remember
Return a result object when the failures are routine and the caller handles each one differently. Throw when the failure is genuinely exceptional and the caller would almost never write specific handling for it.
Related Links
- prewk/resultA PHP implementation of Rust's Result type, referenced in this lesson's libraries section.
- PHP Errors, Exceptions, and Result Types: Designing Failure BoundariesAn article on choosing between exceptions and result types based on who owns a failure and what they can do about it.
- matchThe PHP manual page on the match expression used to handle each result variant.
- UnhandledMatchErrorWhat PHP throws when a match expression does not cover every case, the closest thing to forced exhaustiveness this lesson describes.