2017-02-02 19 views
0

我正在爲授權用戶編寫api。如何在Laravel/Lumen中捕捉401響應?

隨着我當前的代碼,我可以趕上如果響應代碼爲然而 如果響應是401,而不是與我的401響應200相反的錯誤消息的我也抓不住,我收到錯誤頁面。

這是流明

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)); 
     } 

基本模式,如果的StatusCode是200我收到此消息

enter image description here

但是如果狀態代碼是401,它會給出錯誤。

enter image description here

+0

你怎麼調用API? – Alfa

回答

0

應用try catch塊到你的代碼

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

我建議在app\Exceptions\Handler.php處理通用例外。 在這個文件中,存在一個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); 
}