Skip to content
laravel-exceptions logo

Laravel Exceptions

laravel-exceptions

Custom exceptions with static factories and HTTP responses. Use when working with error handling, custom exceptions, or when user mentions exceptions, custom exception, error handling, HTTP exceptions.

SKILL.md

Full skill instructions

Laravel Exceptions

Custom exceptions use static factory methods and implement HttpExceptionInterface.

Related guides:

  • Actions - Throwing exceptions in actions

Structure

<?php

declare(strict_types=1);

namespace App\Exceptions;

use App\Exceptions\Concerns\Httpable;
use App\Models\Order;
use Exception;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;

class OrderException extends Exception implements HttpExceptionInterface
{
    use Httpable;

    public static function notFound(string|int $orderId): self
    {
        return new self("Order {$orderId} not found.", 404);
    }

    public static function cannotCancelOrder(Order $order): self
    {
        return new self(
            "Order {$order->uuid} cannot be cancelled in its current state.",
            400
        );
    }

    public static function insufficientStock(string $productName): self
    {
        return new self(
            "Insufficient stock for product: {$productName}",
            422
        );
    }

    public static function paymentFailed(string $reason): self
    {
        return new self("Payment failed: {$reason}", 402);
    }
}

Httpable Concern

View full implementation →

Usage

Throwing Exceptions

// In actions
throw OrderException::notFound($orderId);
throw OrderException::cannotCancelOrder($order);
throw OrderException::insufficientStock($product->name);

With throw_unless/​throw_if

class CancelOrderAction
{
    public function __invoke(Order $order): Order
    {
        throw_unless(
            $order->canBeCancelled(),
            OrderException::cannotCancelOrder($order)
        );

        // Continue with cancellation
    }
}

Guard Methods

class ProcessOrderAction
{
    public function __invoke(Order $order): void
    {
        $this->guard($order);

        // Process order
    }

    private function guard(Order $order): void
    {
        throw_unless(
            $order->isPending(),
            OrderException::cannotProcessOrder($order)
        );

        throw_unless(
            $order->hasItems(),
            OrderException::orderHasNoItems($order)
        );
    }
}

Key Patterns

1. Static Factory Methods

Named constructors for specific exceptions:

public static function notFound(string|int $orderId): self
{
    return new self("Order {$orderId} not found.", 404);
}

2. HTTP Status Codes

Pass status as second constructor parameter:

new self("Message", 404);  // Not Found
new self("Message", 400);  // Bad Request
new self("Message", 422);  // Unprocessable Entity
new self("Message", 403);  // Forbidden

3. Descriptive Messages

Include context in error messages:

"Order {$order->uuid} cannot be cancelled"
"Insufficient stock for product: {$productName}"

4. HttpExceptionInterface

Implement interface for automatic HTTP error responses:

class OrderException extends Exception implements HttpExceptionInterface
{
    use Httpable;
}

Common HTTP Status Codes

  • 400 - Bad Request (business rule violation)
  • 402 - Payment Required
  • 403 - Forbidden (authorization failed)
  • 404 - Not Found
  • 422 - Unprocessable Entity (validation failed)
  • 500 - Internal Server Error

Directory Structure

app/​Exceptions/
├── OrderException.php
├── PaymentException.php
├── UserException.php
└── Concerns/
    └── Httpable.php

Summary

Exceptions should:

  • Use static factory methods
  • Implement HttpExceptionInterface
  • Include HTTP status codes
  • Have descriptive messages with context
  • Be named {Entity}Exception

Use for business rule violations and error conditions.

More Other skills

Delegate independent tasks to specialized agents working concurrently with isolated context.

295.4K 206.3K
View

Applies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand colors or style guidelines, visual formatting, or company design standards apply.

179.7K 100.1K
View

Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with colors/fonts that you can apply to any artifact that has been creating, or can generate a new theme on-the-fly.

179.7K 89.5K
View

A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill whenever asked to write some sort of internal communications (status reports, leadership updates, 3P updates, company newsletters, FAQs, incident reports, project updates, etc.).

179.7K 76.1K
View

Fundamental design principles for writing maintainable, testable Python code.

40.2K 21.9K
View

Modern responsive layouts using container queries, fluid typography, CSS Grid, and mobile-first strategies.

40.2K 20K
View

Generate Playwright tests from scenarios using interactive browser exploration and validation.

39.7K 18.2K
View

Modern React state management with Redux Toolkit, Zustand, Jotai, and React Query for every state category.

40.2K 14.7K
View

GDPR-compliant data handling with consent management, data subject rights, and privacy controls.

40.2K 14.3K
View

Python error handling patterns including input validation, exception hierarchies, and partial failure handling. Use when implementing validation logic, designing exception strategies, handling batch processing failures, or building robust APIs.

40.2K 13.5K
View

Detailed multi-file refactor planning with safety checks and rollback guidance.

39.7K 13K
View