php – Laravel – 自訂 404 回傳 JSON
Laravel 5.7 預設會回傳 404 的 view。如果我們製作 API 希望回傳的是 JSON 格式的 404,那麼參考以下修改。
app\Exceptions\Handler.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public function render($request, Exception $exception) { if ($this->isHttpException($exception)) { if ($exception->getStatusCode() == 404) { return response(json_encode(['error' => 'Not found.']), 404) ->header('Content-Type', 'application/json'); } } return parent::render($request, $exception); } |