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

推荐订阅源

T
Threat Research - Cisco Blogs
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
The Register - Security
The Register - Security
A
About on SuperTechFans
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
L
LangChain Blog
N
Netflix TechBlog - Medium
量子位
博客园 - 三生石上(FineUI控件)
宝玉的分享
宝玉的分享
H
Help Net Security
D
Docker
D
DataBreaches.Net
T
Tailwind CSS Blog
阮一峰的网络日志
阮一峰的网络日志
B
Blog
博客园 - 聂微东
Apple Machine Learning Research
Apple Machine Learning Research
Google DeepMind News
Google DeepMind News
The Cloudflare Blog
F
Full Disclosure
GbyAI
GbyAI
F
Fortinet All Blogs
Last Week in AI
Last Week in AI
Y
Y Combinator Blog
人人都是产品经理
人人都是产品经理
Recent Announcements
Recent Announcements
博客园 - Franky
MongoDB | Blog
MongoDB | Blog
有赞技术团队
有赞技术团队
博客园 - 叶小钗
小众软件
小众软件
V
Visual Studio Blog
月光博客
月光博客
Stack Overflow Blog
Stack Overflow Blog
The GitHub Blog
The GitHub Blog
Recorded Future
Recorded Future
J
Java Code Geeks
雷峰网
雷峰网
P
Privacy & Cybersecurity Law Blog
C
Cisco Blogs
C
Cyber Attacks, Cyber Crime and Cyber Security
AWS News Blog
AWS News Blog
Webroot Blog
Webroot Blog
美团技术团队
N
News | PayPal Newsroom
G
Google Developers Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
博客园_首页
V
Vulnerabilities – Threatpost

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
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.