2017-02-02 11 views
0

私は承認ユーザーのためにAPIを作成しています。Laravel/Lumenの401応答を取得するには?

応答コードがしかし であれば、私はキャッチすることができます私の現在のコードで

応答が代わりに私の401応答でエラーメッセージの401の代わりに、200であれば、私はキャッチすることはできません、私はエラーページを受け取ります。

からstatusCodeが200であれば基本的に私はこのメッセージ

enter image description here

を受け取るこれはルーメン

if($input['phone']==$this->phone && $input['password'] == $this->password){ 
      return response()->json([ 
      'redirect_uri' => $redirect_uri, 
      'token' => $this->token 
      ]); 
     } 

     return response()->json([ 
      'redirect_uri' => $redirect_uri, 
      'errorMsg' => 'User Not found or id psw wrong' 
      ],401); 

の私の闊歩サーバであり、これはLaravel

if($response->getStatusCode() == 401){ 
      dd('you are not authorized'); 
     } 

     if($response->getStatusCode() == 200){ 
      dd('you are authorized'); 
      //Store user credentials on cache 
      CacheStore::storeUserCredentials(json_decode((string) $response->getBody(), true)); 
     } 

の私のモデルであり、しかし、ステータスコードが401の場合、エラーになります。

enter image description here

+0

がどのようにAPIを呼ぶのですか? – Alfa

答えて

0

私はapp\Exceptions\Handler.phpユニバーサル例外を扱うお勧めしますあなたのコード

try{ 
    // your api call 
} 
catch(Exception $e) 
{ 
    if ($e instanceof HttpException && $e->getStatusCode()== 401) 
    { 
     dd('you are not authorized'); 
    } 
} 
1

へのtry catchブロックを適用します。 このファイルには、render関数が存在します。

が例外の異なる種類に対処するために、あなたが試すことができます:

public function render($request, Exception $e) 
{ 
    if ($e instanceof SomeTypeException1) 
    { 
     #handle it 
    } 
    else if($e instanceof SomeTypeException2) 
    { 
     #handle it 
    } 

    return parent::render($request, $e); 
} 
関連する問題