我正在为授权用户编写一个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 block 应用于您的代码
try{
// your api call
}
catch(Exception $e)
{
if ($e instanceof HttpException && $e->getStatusCode()== 401)
{
dd('you are not authorized');
}
}
关于php - 如何在 Laravel/Lumen 中捕获 401 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41995461/