Open9
Laravel 11.x エラー処理

エラー処理がうまくないことに気づき、キャッチアップするためにメモ

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

abortも使うもの良さそう

$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
こう書いてたけど、Laravel11でどうするんだろう感

->withMiddleware(function (Middleware $middleware) {
//
})
->withExceptions(function (Exceptions $exceptions) {
//
})->withSingletons([
\Illuminate\Contracts\Debug\ExceptionHandler::class
=> \App\Exceptions\Handler::class,
])->create();
こんな感じで行けるのか?

無理そう

ChatGptパイセンに聞いたら良さげなヒントが
下記のようにした
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"
]);
});
}
}

適当なところで
throw new NotFoundHttpException();
とすると、、、
レスポンスが下記に上書きされる
{
"hoge": "fuga"
}
200OK

1行で書くならこう
// 2行バージョン
$exceptionHandler = new Handler();
$exceptionHandler->handleExceptions($exceptions);
// 1行バージョン
(new Handler())->handleExceptions($exceptions);