LoginSignup
2
0

More than 1 year has passed since last update.

【Laravel】デフォルトで出力されない例外(HTTPエラー等)をログに出力する

Last updated at Posted at 2021-08-05

結論

App\Exceptions\Handler.php$internalDontReport配列を、空の配列[]でオーバーライドする。

説明

Laravelの例外はすべてvendor\laravel\framework\src\Illuminate\Foundation\Exceptions\Handlerクラスでcatchされ、ログの出力とユーザへの表示を行います。

ログの出力はreportメソッドが担当しています。

    public function report(Exception $e)
    {
        if ($this->shouldntReport($e)) {
            return;
        }

        if (Reflector::isCallable($reportCallable = [$e, 'report'])) {
            if (($response = $this->container->call($reportCallable)) !== false) {
                return $response;
            }
        }

        try {
            $logger = $this->container->make(LoggerInterface::class);
        } catch (Exception $ex) {
            throw $e;
        }

        $logger->error(
            $e->getMessage(),
            array_merge(
                $this->exceptionContext($e),
                $this->context(),
                ['exception' => $e]
            )
        );
    }

catchしたすべての例外をログに吐き出すようになっていますが、Handlerクラスでは「この例外のログは吐き出さなくていいよ」という指定ができます。それを指定するのが$internalDontReport配列で、デフォルトでは以下が指定されています。

    /**
     * A list of the internal exception types that should not be reported.
     *
     * @var array
     */
    protected $internalDontReport = [
        AuthenticationException::class,         // 認証関連の例外
        AuthorizationException::class,          // 認可関連の例外
        HttpException::class,                   // HTTPリクエスト関連の例外
        HttpResponseException::class,           // HTTPレスポンス関連の例外
        ModelNotFoundException::class,          // モデルが見つからない例外
        SuspiciousOperationException::class,    // ユーザーがセキュリティの観点から疑わしいとみなされる操作を実行した場合に発生
        TokenMismatchException::class,          // 送信されたトークンとDBのトークンが一致しない例外
        ValidationException::class,             // バリデーション
    ];

Handlerクラスはvendor配下だけではなく、アプリケーション作成時にApp\Exceptions\Handler.phpにも継承したクラスが作成されています。こちらに処理を記述することでvendor配下のプロパティ・メソッドをオーバーライドすることができます。

App\Exceptions\Handler.php$internalDontReportを定義してあげることで、例外発生時に優先して参照されるのでvendor配下のコードを汚さずに例外出力の対象を変えることができました:v:

    // App\Exceptions\Handler.phpに以下を追記すれば、すべての例外がログに出力される
    protected $internalDontReport = [
        // AuthenticationException::class,
        // AuthorizationException::class,
        // HttpException::class,
        // HttpResponseException::class,
        // ModelNotFoundException::class,
        // SuspiciousOperationException::class,
        // TokenMismatchException::class,
        // ValidationException::class,
    ];

参考:
https://readouble.com/laravel/7.x/ja/errors.html

2
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
2
0