47
48

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Laravel エラー時のレスポンス形式の変更(JSON)

Posted at

概要

ajax, api のルーティングのグループを作成したが、通常の処理は、JSON形式で返るが、
エラー発生時(400, 404, 500, 503など)の際にHTMLが返ってしまう。

エラーの時にもJSON形式で応答して欲しいので、調べた結果をメモに残す。

例外処理のrenderメソッドで対応する

下記のように特定のURL(ajax,api)などへのリクエストに対してまとめて変更する。

app/Exceptions/handler.php
// レスポンスをJSON形式に変更
if ($request->is('ajax/*') || $request->is('api/*') || $request->ajax()) {
    $status = 400;
    if ($this->isHttpException($exception)) {
        $status = $exception->getStatusCode();
    }
    return response()->json([
        'status' => $status,
        'errors' => $this->getMessage($status)
    ], $status);
}

以上

参考サイト

47
48
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
47
48

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?