Open9

Laravel 11.x エラー処理

capybaraさんcapybaraさん

まずどこに書くか
そこまで規模が大きくない場合、bootstrap/app.phpのwithExceptionsで良さそう?
ただ今まで通りExceptionHandlerのextends に書く方が後々肥大化した時に対応しやすそう

capybaraさんcapybaraさん
$app->singleton(
    Illuminate\Contracts\Debug\ExceptionHandler::class,
    App\Exceptions\Handler::class
);

こう書いてたけど、Laravel11でどうするんだろう感

capybaraさんcapybaraさん
    ->withMiddleware(function (Middleware $middleware) {
        //
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->withSingletons([
        \Illuminate\Contracts\Debug\ExceptionHandler::class 
            => \App\Exceptions\Handler::class,
    ])->create();

こんな感じで行けるのか?

capybaraさんcapybaraさん

ChatGptパイセンに聞いたら良さげなヒントが
https://chatgpt.com/share/56cf9681-bf56-44f3-a86b-e502f5077199

下記のようにした

app.php
use App\Exceptions\Handler;
~~~
    ->withExceptions(function (Exceptions $exceptions) {
        $exceptionHandler = new Handler();
        $exceptionHandler->handleExceptions($exceptions);
~~~
Handler.php

namespace App\Exceptions;

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class Handler
{
    public function handleExceptions($exceptions)
    {
        $exceptions->render(function (NotFoundHttpException $e, Request $request) {
            return response()->json([
                "hoge" => "fuga"
            ]);
        });
    }
}
capybaraさんcapybaraさん

適当なところで

throw new NotFoundHttpException();

とすると、、、
レスポンスが下記に上書きされる

{
    "hoge": "fuga"
}

200OK

capybaraさんcapybaraさん

1行で書くならこう

// 2行バージョン
$exceptionHandler = new Handler();
$exceptionHandler->handleExceptions($exceptions);

// 1行バージョン
(new Handler())->handleExceptions($exceptions);