Readouble

Laravel 5.7 エラー処理

イントロダクションIntroduction

新しいLaravelプロジェクトを開始する時点で、エラーと例外の処理は既に設定済みです。App\Exceptions\Handlerクラスはアプリケーションで発生する全例外をログし、ユーザーへ表示するためのクラスです。このドキュメントでは、このクラスの詳細を確認していきます。When you start a new Laravel project, error and exception handling is already configured for you. The App\Exceptions\Handler class is where all exceptions triggered by your application are logged and then rendered back to the user. We'll dive deeper into this class throughout this documentation.

設定Configuration

アプリケーションエラー発生時にユーザーに対し表示する詳細の表示量は、config/app.php設定ファイルのdebug設定オプションで決定します。デフォルト状態でこの設定オプションは、.envファイルで指定されるAPP_DEBUG環境変数の値を反映します。The debug option in your config/app.php configuration file determines how much information about an error is actually displayed to the user. By default, this option is set to respect the value of the APP_DEBUG environment variable, which is stored in your .env file.

local環境ではAPP_DEBUG環境変数をtrueに設定すべきでしょう。実働環境ではこの値をいつもfalseにすべきです。実働環境でこの値をtrueにしてしまうと、アプリケーションのエンドユーザーへ、セキュリティリスクになりえる設定情報を表示するリスクを犯すことになります。For local development, you should set the APP_DEBUG environment variable to true. In your production environment, this value should always be false. If the value is set to true in production, you risk exposing sensitive configuration values to your application's end users.

例外ハンドラThe Exception Handler

reportメソッドThe Report Method

例外はすべて、App\Exceptions\Handlerクラスで処理されます。このクラスはreportrender二つのメソッドで構成されています。両メソッドの詳細を見ていきましょう。reportメソッドは例外をログするか、BugSnagSentryのような外部サービスに送信するために使います。デフォルト状態のreportメソッドは、渡された例外をベースクラスに渡し、そこで例外はログされます。しかし好きなように例外をログすることが可能です。All exceptions are handled by the App\Exceptions\Handler class. This class contains two methods: report and render. We'll examine each of these methods in detail. The report method is used to log exceptions or send them to an external service like Bugsnag[https://bugsnag.com] or Sentry[https://github.com/getsentry/sentry-laravel]. By default, the report method passes the exception to the base class where the exception is logged. However, you are free to log exceptions however you wish.

たとえば異なった例外を別々の方法レポートする必要がある場合、PHPのinstanceof比較演算子を使ってください。For example, if you need to report different types of exceptions in different ways, you may use the PHP instanceof comparison operator:

/**
 * 例外をレポート、もしくはログする
 *
 * ここは例外をSentryやBugsnagなどへ送るために適した場所
 *
 * @param  \Exception  $exception
 * @return void
 */
public function report(Exception $exception)
{
    if ($exception instanceof CustomException) {
        //
    }

    parent::report($exception);
}

lightbulb">Tip!! reportメソッド中で数多くのinstanceofチェックを行う代わりに、reportable exceptionsの使用を考慮してください。{tip} Instead of making a lot of instanceof checks in your report method, consider using reportable exceptions[/docs/{{version}}/errors#renderable-exceptions]

reportヘルパThe report Helper

場合により、例外をレポートする必要があるが、現在のリクエストの処理を継続したい場合があります。reportヘルパ関数により、エラーページをレンダすること無く、例外ハンドラのreportメソッドを使用し、例外を簡単にレポートできます。Sometimes you may need to report an exception but continue handling the current request. The report helper function allows you to quickly report an exception using your exception handler's report method without rendering an error page:

public function isValid($value)
{
    try {
        // 値の確認…
    } catch (Exception $e) {
        report($e);

        return false;
    }
}

タイプによる例外の無視Ignoring Exceptions By Type

例外ハンドラの$dontReportプロパティは、ログしない例外のタイプの配列で構成します。たとえば、404エラー例外と同様に、他のタイプの例外もログしたくない場合です。必要に応じてこの配列へ、他の例外を付け加えてください。The $dontReport property of the exception handler contains an array of exception types that will not be logged. For example, exceptions resulting from 404 errors, as well as several other types of errors, are not written to your log files. You may add other exception types to this array as needed:

/**
 * レポートしない例外のリスト
 *
 * @var array
 */
protected $dontReport = [
    \Illuminate\Auth\AuthenticationException::class,
    \Illuminate\Auth\Access\AuthorizationException::class,
    \Symfony\Component\HttpKernel\Exception\HttpException::class,
    \Illuminate\Database\Eloquent\ModelNotFoundException::class,
    \Illuminate\Validation\ValidationException::class,
];

renderメソッドThe Render Method

renderメソッドは与えられた例外をブラウザーに送り返すHTTPレスポンスへ変換することに責任を持っています。デフォルトで例外はベースクラスに渡され、そこでレスポンスが生成されます。しかし例外のタイプをチェックし、お好きなようにレスポンスを返してかまいません。The render method is responsible for converting a given exception into an HTTP response that should be sent back to the browser. By default, the exception is passed to the base class which generates a response for you. However, you are free to check the exception type or return your own custom response:

/**
 * HTTPレスポンスへ例外をレンダー
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Exception  $exception
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $exception)
{
    if ($exception instanceof CustomException) {
        return response()->view('errors.custom', [], 500);
    }

    return parent::render($request, $exception);
}

Reportable/Renderable例外Reportable & Renderable Exceptions

例外ハンドラの中のreportrenderメソッドの中で、例外のタイプをチェックする代わりに、自身のカスタム例外でreportrenderメソッドを定義できます。これらのメソッドが存在すると、フレームワークにより自動的に呼び出されます。Instead of type-checking exceptions in the exception handler's report and render methods, you may define report and render methods directly on your custom exception. When these methods exist, they will be called automatically by the framework:

<?php

namespace App\Exceptions;

use Exception;

class RenderException extends Exception
{
    /**
     * 例外のレポート
     *
     * @return void
     */
    public function report()
    {
        //
    }

    /**
     * 例外をHTTPレスポンスへレンダ
     *
     * @param  \Illuminate\Http\Request
     * @return \Illuminate\Http\Response
     */
    public function render($request)
    {
        return response(...);
    }
}

HTTP例外HTTP Exceptions

例外の中にはサーバでのHTTPエラーコードを表しているものがあります。たとえば「ページが見つかりません」エラー(404)や「未認証エラー」(401)、開発者が生成した500エラーなどです。アプリケーションのどこからでもこの種のレスポンスを生成するには、abortヘルパを使用します。Some exceptions describe HTTP error codes from the server. For example, this may be a "page not found" error (404), an "unauthorized error" (401) or even a developer generated 500 error. In order to generate such a response from anywhere in your application, you may use the abort helper:

abort(404);

abortヘルパは即座に例外を発生させ、その例外は例外ハンドラによりレンダーされることになります。オプションとしてレスポンスのテキストを指定することもできます。The abort helper will immediately raise an exception which will be rendered by the exception handler. Optionally, you may provide the response text:

abort(403, 'Unauthorized action.');

カスタムHTTPエラーページCustom HTTP Error Pages

様々なHTTPステータスコードごとに、Laravelはカスタムエラーページを簡単に返せます。たとえば404 HTTPステータスコードに対してカスタムエラーページを返したければ、resources/views/errors/404.blade.phpを作成してください。このファイルはアプリケーションで起こされる全404エラーに対し動作します。ビューはこのディレクトリに置かれ、対応するHTTPコードと一致した名前にしなくてはなりません。abortヘルパが生成するHttpExceptionインスタンスは、$exception変数として渡されます。Laravel makes it easy to display custom error pages for various HTTP status codes. For example, if you wish to customize the error page for 404 HTTP status codes, create a resources/views/errors/404.blade.php. This file will be served on all 404 errors generated by your application. The views within this directory should be named to match the HTTP status code they correspond to. The HttpException instance raised by the abort function will be passed to the view as an $exception variable:

<h2>{{ $exception->getMessage() }}</h2>

Laravelのエラーページテンプレートは、vendor:publish Artisanコマンドで公開できます。テンプレートを公開したら、好みのようにカスタマイズできます。You may publish Laravel's error page templates using the vendor:publish Artisan command. Once the templates have been published, you may customize them to your liking:

php artisan vendor:publish --tag=laravel-errors

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作