[英]How to catch 401 response in Laravel/Lumen?
我正在為授權用戶編寫一個 api。
使用我當前的代碼,如果響應代碼是200,我可以捕獲,但是如果響應是 401 而不是200,我無法捕獲。我收到錯誤頁面,而不是帶有 401 響應的錯誤消息。
這是我在 Lumen 中的 swagger 服務器
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));
}
基本上如果狀態碼是 200 我收到這條消息
但是如果狀態代碼是 401,它就會出錯。
將 try catch 塊應用於您的代碼
try{
// your api call
}
catch(Exception $e)
{
if ($e instanceof HttpException && $e->getStatusCode()== 401)
{
dd('you are not authorized');
}
}
我建議在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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.