1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Laravel12のミドルウェア 例外処理 検証

Last updated at Posted at 2025-05-26

前回の記事の続きからの続き。
https://qiita.com/pig_buhi555/items/15594aa216a9deaa6c87

ミドルウェアの例外処理について、個人的なメモとして書いていく。

withExceptionsの箇所に処理を追加している。

1. ソース

laravel12/bootstrap/app.php
<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use App\Http\Middleware\AppendMiddleware;
use App\Http\Middleware\CustomEmptyStringsToNull;
use App\Http\Middleware\PrependMiddleware;
use Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull;
use App\Exceptions\Handler;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        /*** ここに使用するMiddleware記載 ***/
        /*** php artisan make:middleware ミドルウェア名 で作成 ***/
        // 最初に追加
        $middleware->prepend(PrependMiddleware::class);
        
        // 最後に追加
        $middleware->append(AppendMiddleware::class);
        // デフォルトのミドルウェアの書き換え
        $middleware->replace(ConvertEmptyStringsToNull::class, CustomEmptyStringsToNull::class);

        // ミドルウェア削除(例. PrependMiddleware)
        $middleware->remove(PrependMiddleware::class);
        // PrependMiddlewareは実行されない
        $middleware->prepend(PrependMiddleware::class);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
        $exceptionHandler = new Handler();
        $exceptionHandler->handleExceptions($exceptions);
    })->create();

ここでは、前回作成したファイルでthrowを行う。

laravel12/app/Http/Middleware/AppendMiddleware.php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class AppendMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        throw new NotFoundHttpException();
        logger('AppendMiddleware');
        return $next($request);
    }
}

以下のartisanコマンドでHandlerクラスを作成し修正。

php artisan make:exception Handler
laravel12/app/Exceptions/Handler.php
<?php

namespace App\Exceptions;

use Exception;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Illuminate\Http\Request;

class Handler extends Exception
{
    public function handleExceptions($exceptions)
    {
        logger('Handler');
        $exceptions->render(function (NotFoundHttpException $e, Request $request) {
            return response()->view('welcome');
        });
    }
}

2. URLにアクセス

3. ログ

laravel12/storage/logs/laravel.log
[2025-05-26 07:10:18] local.DEBUG: CustomEmptyStringsToNull  
[2025-05-26 07:10:18] local.DEBUG: Handler  

4. 参考

ありがとうございました。
https://zenn.dev/dialog_capybara/scraps/d04772c884ed28

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?