laravel-exceptions について
Laravel の開発者向けに、業務エラーを HTTP レスポンスに結び付ける例外処理の指針を示します。静的ファクトリーメソッド、HTTP ステータスコード、状況を示すメッセージで独自例外を構成します。
主な機能
- 01静的ファクトリーメソッドで例外を作成
- 02HttpExceptionInterface を実装
- 03HTTP ステータスコードを関連付け
- 04エラーメッセージに状況を記載
活用シーン
- 01業務ルール違反の表現
- 02リソース未発見エラーの処理
- 03Action の事前条件の確認
インストール
コマンドをコピーしてターミナルで実行します。
$
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 トレイト
使用方法
例外をスローする
// 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
}
}
ガードメソッド
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 ステータスコード
ステータスをコンストラクターの第 2 引数として渡します:
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 対応