[英]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.