ホームページ  >  記事  >  バックエンド開発  >  Lumen が Laravel5 のようなユーザーフレンドリーなエラーページを実装する方法

Lumen が Laravel5 のようなユーザーフレンドリーなエラーページを実装する方法

WBOY
WBOYオリジナル
2016-06-20 12:48:41995ブラウズ

Laravel5 でユーザーフレンドリーなエラーページを実装するのは非常に簡単です。たとえば、ステータス 404 を返したい場合は、view/errors に 404.blade.php ファイルを追加するだけです。 Lumen はデフォルトではこの便利さを実装していないため、自分で追加しました。

Lumen が Laravel5 のようなユーザーフレンドリーなエラーページを実装する方法

原理

エラーをスローする関数は abort() です。関数を入力して見てみると、次のことがわかります。アプリケーションでは http リクエストを処理するときに try catch プロセスがあり、ここで Exception がキャッチされます。

try {    return $this->sendThroughPipeline($this->middleware, function () use ($method, $pathInfo) {        if (isset($this->routes[$method.$pathInfo])) {            return $this->handleFoundRoute([true, $this->routes[$method.$pathInfo]['action'], []]);        }        return $this->handleDispatcherResponse(            $this->createDispatcher()->dispatch($method, $pathInfo)        );    });} catch (Exception $e) {    return $this->sendExceptionToHandler($e);}

例外が sendExceptionToHandler に渡されて処理されていることがわかります。ここでのハンドラーはどの特定のクラスですか? IlluminateContractsDebugExceptionHandler を実装するシングルトンです。なぜ彼がシングルトンだと言えるのですか?ブートストラップ時にシングルトンとして初期化されていますのでご覧ください。

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

このクラスに入り、render メソッドがあることを確認してください。問題が見つかりました。このメソッドを変更するだけです。

public function render($request, Exception $e){    return parent::render($request, $e);}

実践的な修正

Laravel では既に実装されているため、コピー&ペーストが最も簡単な方法です。レンダリングでは、まず HttpException であるかどうかを判断し、エラー ディレクトリに移動してステータス コードに対応するビューを見つけます。見つかった場合は、それをレンダリングして出力します。それはとても簡単です。ハンドラーを次のように変更します。

/** * Render an exception into an HTTP response. * * @param  \Illuminate\Http\Request  $request * @param  \Exception  $e * @return \Illuminate\Http\Response */public function render($request, Exception $e){    if( !env('APP_DEBUG') and $this->isHttpException($e)) {        return $this->renderHttpException($e);    }    return parent::render($request, $e);}/** * Render the given HttpException. * * @param  \Symfony\Component\HttpKernel\Exception\HttpException  $e * @return \Symfony\Component\HttpFoundation\Response */protected function renderHttpException(HttpException $e){    $status = $e->getStatusCode();    if (view()->exists("errors.{$status}"))    {        return response(view("errors.{$status}", []), $status);    }    else    {        return (new SymfonyExceptionHandler(env('APP_DEBUG', false)))->createResponse($e);    }}/** * Determine if the given exception is an HTTP exception. * * @param  \Exception  $e * @return bool */protected function isHttpException(Exception $e){    return $e instanceof HttpException;}

それでは、errors ディレクトリに新しい 404.blade.php ファイルを作成し、コントローラーで abort(404) を試してみてください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。