惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

宝玉的分享
宝玉的分享
B
Blog RSS Feed
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
MyScale Blog
MyScale Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
S
SegmentFault 最新的问题
Y
Y Combinator Blog
月光博客
月光博客
IT之家
IT之家
T
Tailwind CSS Blog
Last Week in AI
Last Week in AI
L
LangChain Blog
博客园_首页
MongoDB | Blog
MongoDB | Blog
P
Proofpoint News Feed
博客园 - Franky
WordPress大学
WordPress大学
云风的 BLOG
云风的 BLOG
M
MIT News - Artificial intelligence
V
Visual Studio Blog
小众软件
小众软件
博客园 - 叶小钗
博客园 - 三生石上(FineUI控件)
N
Netflix TechBlog - Medium

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Taming Error Handling in Laravel with Custom Exceptions
Gavin Sykes · 2026-06-22 · via DEV Community

When you're building a Laravel application, it's tempting to reach for abort() whenever something goes wrong, let's take a flight booking app. trying to check a user in to a flight:

abort(422, 'Passenger has already checked in.');
abort(403, 'Boarding has closed for this flight.');
abort(404, 'Booking not found.');

For a quick controller method, this feels fine. But as your application grows — with services, actions, jobs, and console commands all sharing the same business logic — those abort() calls start to become a problem.

The Problem with abort() Everywhere

The abort() helper works by throwing an HttpException and is designed for HTTP contexts. The moment your business logic lives outside a controller — in an action class, a service, a queued job, or a CLI command — abort() becomes the wrong tool entirely.

Consider a CheckInAction that might be called from:

  • A controller handling a web or API request
  • A Filament action button for airport staff
  • (Okay, British Airways probably aren't using Filament, but there's a much better chance that your app is!)
  • A queued job processing an automated check-in

If that action calls abort(422, 'Seat is no longer available'), it works fine from a controller, but it's semantically wrong from a job or command — and if you ever write a unit test for it, you'll be asserting against HttpException instead of something that actually describes your domain.

There's a better way.


Custom Exceptions as Domain Signals

The pattern has three parts:

  1. A base exception for each domain concept, with a getKey() method that maps the failure to a form field
  2. Concrete exception classes that extend it, one per failure scenario
  3. A controller catch that converts any domain failure into a ValidationException — giving the frontend a consistent, familiar error shape

This keeps HTTP concerns out of your business logic entirely, while ensuring the controller can surface errors to users in a way they'll understand.

Here's what that looks like for a flight check-in system.

Step 1: Define a Base Exception

All check-in failures extend a common base class. The key design decision here is getKey(): each exception knows which form field it relates to, so when the error surfaces as a validation message, it can target the right field.

// app/Exceptions/CheckInException.php
namespace App\Exceptions;

use RuntimeException;

abstract class CheckInException extends RuntimeException
{
    abstract public function getKey(): string;
}

Step 2: Define Your Concrete Exceptions

Create a dedicated class for each failure scenario. Each one knows its message and its key:

// app/Exceptions/CheckIn/AlreadyCheckedInException.php
namespace App\Exceptions\CheckIn;

use App\Exceptions\CheckInException;

class AlreadyCheckedInException extends CheckInException
{
    public function __construct(string $bookingReference)
    {
        parent::__construct(__("Booking :bookingReference has already been checked in.", [
            'bookingReference' => $bookingReference,
        ]));
    }

    public function getKey(): string
    {
        return 'booking_reference';
    }
}

// app/Exceptions/CheckIn/BoardingClosedException.php
namespace App\Exceptions\CheckIn;

use App\Exceptions\CheckInException;

class BoardingClosedException extends CheckInException
{
    public function __construct(string $flightNumber)
    {
        parent::__construct(__("Boarding has closed for flight :flightNumber.", [
            'flightNumber' => $flightNumber,
        ]));
    }

    public function getKey(): string
    {
        return 'flight';
    }
}

// app/Exceptions/CheckIn/SeatUnavailableException.php
namespace App\Exceptions\CheckIn;

use App\Exceptions\CheckInException;

class SeatUnavailableException extends CheckInException
{
    public function __construct(string $seatNumber)
    {
        parent::__construct(__("Seat :seatNumber is no longer available.", [
            'seatNumber' => $seatNumber,
        ]));
    }

    public function getKey(): string
    {
        return 'seat_number';
    }
}

// app/Exceptions/CheckIn/DocumentsIncompleteException.php
namespace App\Exceptions\CheckIn;

use App\Exceptions\CheckInException;

class DocumentsIncompleteException extends CheckInException
{
    public function __construct(array $missingDocuments)
    {
        $list = implode(', ', $missingDocuments);
        parent::__construct(__("Check-in cannot proceed. Missing documents: :list.", [
            'list' => $list,
        ]));
    }

    public function getKey(): string
    {
        return 'documents';
    }
}

Step 3: Throw Them in Your Business Logic

Your action takes plain data — a Booking model and a seat number — with no knowledge of where that data came from. It just describes a business process and throws domain exceptions when that process can't continue.

A nice way to structure this is to extract each guard into a private assertX() method. The handle() method then reads like a checklist of preconditions, and each private method carries a @throws docblock so your IDE knows exactly which exceptions can bubble up from each call:

// app/Actions/CheckInAction.php
namespace App\Actions;

use App\Exceptions\CheckIn\AlreadyCheckedInException;
use App\Exceptions\CheckIn\BoardingClosedException;
use App\Exceptions\CheckIn\DocumentsIncompleteException;
use App\Exceptions\CheckIn\SeatUnavailableException;
use App\Models\Booking;

class CheckInAction
{
    private Booking $booking;
    private string $seatNumber;

    /**
     * @throws AlreadyCheckedInException
     * @throws BoardingClosedException
     * @throws DocumentsIncompleteException
     * @throws SeatUnavailableException
     */
    public function handle(Booking $booking, string $seatNumber): void
    {
        $this->booking = $booking;
        $this->seatNumber = $seatNumber;

        $this->assertNotAlreadyCheckedIn();
        $this->assertBoardingHasNotClosed();
        $this->assertDocumentsAreComplete();
        $this->assertSeatIsAvailable();

        $this->booking->update([
            'seat_number'   => $this->seatNumber,
            'is_checked_in' => true,
            'checked_in_at' => now(),
        ]);
    }

    /**
     * @throws AlreadyCheckedInException
     */
    private function assertNotAlreadyCheckedIn(): void
    {
        if ($this->booking->is_checked_in) {
            throw new AlreadyCheckedInException($this->booking->reference);
        }
    }

    /**
     * @throws BoardingClosedException
     */
    private function assertBoardingHasNotClosed(): void
    {
        if ($this->booking->flight->boarding_closed_at->isPast()) {
            throw new BoardingClosedException($this->booking->flight->number);
        }
    }

    /**
     * @throws DocumentsIncompleteException
     */
    private function assertDocumentsAreComplete(): void
    {
        $missingDocs = $this->booking->passenger->missingDocuments();

        if (!empty($missingDocs)) {
            throw new DocumentsIncompleteException($missingDocs);
        }
    }

    /**
     * @throws SeatUnavailableException
     */
    private function assertSeatIsAvailable(): void
    {
        if (!$this->booking->flight->isSeatAvailable($this->seatNumber)) {
            throw new SeatUnavailableException($this->seatNumber);
        }
    }
}

The handle() method is now a clean sequence of named preconditions — no inline conditionals, no throw statements cluttering the main flow. And because each assertX() method declares what it throws, your IDE can surface the full set of possible exceptions at any call site without you having to trace through the implementation.

Bonus: Extract Shared Assertions into Traits

If multiple actions, controllers, jobs, or commands all need to make the same assertion, extract it into a trait:

// app/Concerns/AssertsSeatIsAvailable.php
namespace App\Concerns;

use App\Exceptions\CheckIn\SeatUnavailableException;

trait AssertsSeatIsAvailable
{
    /**
     * @throws SeatUnavailableException
     */
    private function assertSeatIsAvailable(): void
    {
        if (!$this->booking->flight->isSeatAvailable($this->seatNumber)) {
            throw new SeatUnavailableException($this->seatNumber);
        }
    }
}

Then any class that needs it just pulls it in:

class CheckInAction
{
    use AssertsSeatIsAvailable;

    // ...
}

class UpgradeSeatsAction
{
    use AssertsSeatIsAvailable;

    // ...
}

The @throws docblock travels with the trait, so your IDE still knows what can bubble up — and the assertion logic lives in exactly one place.

Step 4: Catch at the Base Class in Your Controller

The controller catches CheckInException — the base type — and converts it into a ValidationException. It doesn't need to know about individual exception types. Each exception already carries its own key and message:

// app/Http/Controllers/CheckInController.php
namespace App\Http\Controllers;

use App\Actions\CheckInAction;
use App\Exceptions\CheckInException;
use App\Http\Requests\CheckInRequest;
use App\Models\Booking;
use Illuminate\Validation\ValidationException;

class CheckInController
{
    public function __invoke(CheckInRequest $request, Booking $booking, CheckInAction $action)
    {
        try {
            $action->handle($booking, $request->seat_number);
        } catch (CheckInException $e) {
            throw ValidationException::withMessages([$e->getKey() => $e->getMessage()]);
        }

        return response()->json(['message' => 'Check-in successful.']);
    }
}

The beauty of converting to ValidationException is that the frontend gets Laravel's standard error shape:

{
    "message": "Seat 14A is no longer available.",
    "errors": {
        "seat_number": ["Seat 14A is no longer available."]
    }
}

Your frontend almost certainly already knows how to handle this — it's the same shape produced by form request validation. The seat_number field gets highlighted, the message appears in the right place, and nothing special needs to be wired up on the client side.


The Payoff: Other Callers Handle What They Care About

Because the exceptions are plain domain objects, every other caller can handle them in a way that makes sense for its context.

A queued job might catch specific exceptions to decide whether to retry:

public function handle(CheckInAction $action): void
{
    try {
        $action->handle($this->booking, $this->seatNumber);
    } catch (SeatUnavailableException $e) {
        // Try to assign a different seat instead
        $this->reassignSeat();
    } catch (BoardingClosedException $e) {
        // No point retrying — fail cleanly
        $this->fail($e);
    }
}

A Filament action can notify staff inline without any HTTP wiring:

Action::make('checkIn')
    ->action(function (Booking $record) use ($action) {
        try {
            $action->handle($record, $record->requested_seat);
        } catch (CheckInException $e) {
            Notification::make()
                ->title('Check-in failed')
                ->body($e->getMessage())
                ->danger()
                ->send();
        }
    })

A unit test asserts exactly the right thing failed:

public function test_cannot_check_in_twice(): void
{
    $booking = Booking::factory()->checkedIn()->create();

    $this->expectException(AlreadyCheckedInException::class);

    (new CheckInAction)->handle($booking, '14A');
}

None of these callers are dealing with HttpException or status codes. They catch what went wrong in terms their context understands.


Why Not Just Use the Global Exception Handler?

You might wonder why the controller does the catching rather than registering everything in Handler.php (or bootstrap/app.php in Laravel 11+). Both approaches work, but the controller catch has some advantages:

It keeps the response format decision local. The ValidationException format is a deliberate choice for this endpoint. A different controller — say, one used by an internal dashboard — might want a different response shape. If you centralise the rendering in the handler, that choice is global.

ValidationException plays nicely with the frontend for free. Rather than crafting a custom JSON response, you get Laravel's standard error structure, which most frontend frameworks and validation libraries already handle.

The handler is better for cross-cutting concerns. Logging, reporting to Sentry, returning a generic 500 page — those belong in the global handler. The specifics of how a particular endpoint surfaces domain errors belong with the controller.


Summary

Approach Where it belongs Downsides
abort(422, '...') Quick controller code only Ties business logic to HTTP; breaks outside controllers
Custom exception + global handler Cross-cutting HTTP rendering Response format is global; harder to vary per endpoint
Custom exception + controller catch → ValidationException Domain logic called from controllers, jobs, and commands Slightly more setup, but the right separation of concerns

The pattern is a small upfront investment that pays off the moment your business logic is called from anywhere other than a controller. Your actions stay clean, your tests become precise, and your frontend gets a consistent error format without any custom wiring — because ValidationException is already the shape it expects.