facebook twitter hatena line email

Php/laravel/laravel5/exception

提供: 初心者エンジニアの簡易メモ
2018年2月16日 (金) 10:01時点におけるAdmin (トーク | 投稿記録)による版 (その他パターンはこちらに書いてある)

移動: 案内検索

404や403や500をカスタマイズする場合

app/Exceptions/Handler.php

public function render($request, Exception $exception)
{
       if ($this->isHttpException($exception)) {
           if ($exception->getStatusCode() == 404) {
               return response()->make("404");
           } elseif ($exception->getStatusCode() == 500) {
               return response()->make("500");
           }
       }
   return parent::render($request, $exception);
}

jsonにする場合

app/Exceptions/Handler.php

return response()->json([
       'status' => 500,
       'errors' => $this->getMessage(500)
   ], 500);

viewに渡す場合

app/Exceptions/Handler.php

if($e->getStatusCode() == 403) {
     return response()->view('errors.403');
}

responseのメソッドはこちらに書いてある

vendor/laravel/framework/src/Illuminate/Contracts/Routing/ResponseFactory.php

make($content = , $status = 200, array $headers = [])
view($view, $data = [], $status = 200, array $headers = [])
json($data = [], $status = 200, array $headers = [], $options = 0)
jsonp($callback, $data = [], $status = 200, array $headers = [], $options = 0)
stream($callback, $status = 200, array $headers = [])
download($file, $name = null, array $headers = [], $disposition = 'attachment')
redirectTo($path, $status = 302, $headers = [], $secure = null)
redirectToRoute($route, $parameters = [], $status = 302, $headers = [])
redirectToAction($action, $parameters = [], $status = 302, $headers = [])
redirectGuest($path, $status = 302, $headers = [], $secure = null)
redirectToIntended($default = '/', $status = 302, $headers = [], $secure = null)