【问题标题】:How to catch 401 response in Laravel/Lumen?如何在 Laravel/Lumen 中捕获 401 响应?
【发布时间】:2017-06-19 03:00:59
【问题描述】:

我正在编写一个用于授权用户的 api。

如果响应代码为 200,我可以使用我当前的代码捕获 如果响应是 401 而不是 200,我无法捕捉到。我收到的 401 响应没有出现错误消息,而是收到错误页面。

这是我在 Lumen 中的招摇服务器

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 就会报错。

【问题讨论】:

  • 如何调用 API?

标签: php laravel api lumen


【解决方案1】:

将 try catch 块应用于您的代码

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

【讨论】:

    【解决方案2】:

    我建议在app\Exceptions\Handler.php 中处理通用异常。 在这个文件中,存在一个render函数。

    要处理不同类型的Exception,可以尝试:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-30
      • 2016-09-14
      • 2016-12-14
      • 2017-10-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多