LoginSignup
0
0

More than 1 year has passed since last update.

【Laravel】401エラーでリダイレクトせずに任意のメッセージを返す方法

Posted at

環境

Laravel v9.5.1 (PHP v8.1.3)

前提

401エラー時に、middleware authがログインのエンドポイントにリダイレクトするようになっているのを

{
  "message" => "Unauthorized"
}

と返ってくるようにしたい。

方法

Handlerに下記を追記。
AuthenticationExceptionunauthenticatedメソッドをオーバーライドする。
これでやりたいエラーメッセージの形と401コードを返してくれる。

app/Exceptions/Handler.php
  use Illuminate\Auth\AuthenticationException;

  protected function unauthenticated($request, AuthenticationException $e): JsonResponse
  {
    $errorMessage = [
      'message' => "Unauthorized",
    ];

    return (new ErrorResource($errorMessage))->response()->setStatusCode(401);
  }

ErrorResourceを使ってエラーレスポンスを統一した記事は↓

参考

0
0
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
0
0