mcpField
L
laravel-exceptions

laravel-exceptions

github.com/leeovery开发1549 次安装2 周前更新
代码仓库

关于 laravel-exceptions

为 Laravel 项目提供异常处理约定,适合希望将业务错误转换为 HTTP 响应的开发者。通过静态工厂方法、HTTP 状态码和描述性消息组织自定义异常。

主要功能

  1. 01静态工厂方法创建异常
  2. 02实现 HttpExceptionInterface
  3. 03关联 HTTP 状态码
  4. 04错误消息包含上下文

适用场景

  1. 01表示业务规则冲突
  2. 02处理资源未找到错误
  3. 03在 Action 中检查操作条件

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/leeovery/agentic-skills --skill laravel-exceptions

安装后在 Claude Code 中输入/laravel-exceptions确认已加载。

附带文件references/Httpable.php

详细介绍

Laravel 异常

自定义异常使用静态工厂方法,并实现 HttpExceptionInterface。

相关指南:

  • 操作 - 在操作中抛出异常

结构

<?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 Trait

查看完整实现 →

用法

抛出异常
// In actions
throw OrderException::notFound($orderId);
throw OrderException::cannotCancelOrder($order);
throw OrderException::insufficientStock($product->name);
与 throw_unless/throw_if 一起使用
class CancelOrderAction
{
    public function __invoke(Order $order): Order
    {
        throw_unless(
            $order->canBeCancelled(),
            OrderException::cannotCancelOrder($order)
        );

        // Continue with cancellation
    }
}
Guard 方法
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)
        );
    }
}

关键模式

1. 静态工厂方法

针对特定异常的命名构造方法:

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

将状态码作为第二个构造函数参数传入:

new self("Message", 404);  // Not Found
new self("Message", 400);  // Bad Request
new self("Message", 422);  // Unprocessable Entity
new self("Message", 403);  // Forbidden
3. 描述性消息

在错误消息中包含上下文:

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

实现此接口以自动生成 HTTP 错误响应:

class OrderException extends Exception implements HttpExceptionInterface
{
    use Httpable;
}

常见 HTTP 状态码

  • 400 - 错误请求(违反业务规则)
  • 402 - 需要付款
  • 403 - 禁止访问(授权失败)
  • 404 - 未找到
  • 422 - 无法处理的实体(验证失败)
  • 500 - 内部服务器错误

目录结构

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

总结

异常应当:

  • 使用静态工厂方法
  • 实现 HttpExceptionInterface
  • 包含 HTTP 状态码
  • 使用包含上下文的描述性消息
  • 命名为 {Entity}Exception

用于处理违反业务规则和错误情况。

评论

支持 Markdown