Quantcast
Viewing all articles
Browse latest Browse all 59

Laravel5で全てのエラーで任意のエラーページを出力する

なんていうかですね、結局WEBサイト制作で要求されることって見てくれなんですよ。運用中にちょっとでもいいシステムにしましょうねなんていう寝言をいうと「はあ?」って話になるので、もうそういうのどうでもいいです。
デフォルトではSymfonyのエラー画面が出ます。Laravel5で任意のエラー画面を出したい時は、
app/Exceptions/Handler.php
を直接いじります。デフォルトだと以下のようになっていて、例外処理を受けている部分があるんですが、returnのところを任意のページにしてあげることができます。

public function render($request, Exception $e)
{
    if ($e instanceof ModelNotFoundException) {
        $e = new NotFoundHttpException($e->getMessage(), $e);
    }

    return parent::render($request, $e);
}
エラー500で返したいときは、

return parent::render($request, $e);

return $this->renderHttpException(new HttpException(500, $e->getMessage(), $e));

500エラーになるのでblaleで500.blade.php
自分で作成したエラーページとかに飛ばしたいときは、あらかじめviewを作っておいてリダイレクトさせればいいです。

return parent::render($request, $e);

$errordode = ‘例外的なエラーです。’;
return redirect(‘/error/’.$errordode);

みたいな感じでできます。

結局、こんな感じとか。

public function render($request, Exception $e)
{
    if (config('app.debug')) {
        return parent::render($request, $e);
    }

    if ($this->isHttpException($e)) {
        $errordode = 'エラー出ました';
        return redirect('/error/'.$errordode);
    } else {
        return $this->renderHttpException(new HttpException(500, $e->getMessage(), $e));
    }
}
本番環境にもっていったらどっちにしろここら辺りをやらないとダメですね。

https://gist.github.com/nazo/d206a8170a075038442c

Viewing all articles
Browse latest Browse all 59

Trending Articles