【问题标题】:Laravel 5: Guzzle -> getStatusCode on Exception?Laravel 5:Guzzle -> getStatusCode 异常?
【发布时间】:2019-06-19 02:20:58
【问题描述】:

我正在为自己编写一个小应用程序。此应用程序正在使用包Guzzle 调用不同的网站。

但是,我想将每个请求与时间和请求持续时间以及我获得的请求状态代码一起存储在我的数据库中。我现在在这里面临的问题是我不知道在请求失败时如何获取http状态码..

这是我目前的代码:

$client = $this->getGuzzleClient();
$request = $client->post($url, $headers, $value);
try {
    $response = $request->send();
    return $response->getBody();
}catch (\GuzzleHttp\Exception\RequestException $e){
    dd(array($e, $e->getResponse()));
}

$e->getResponse() 返回null。我也尝试使用$e->getStatusCode()$e->getRequest()->getStatusCode()。两者都不工作......

为了绝对确定请求是有效的,我会处理一个真正的例外,我打电话给这个网站https://httpstat.us/503。这会返回一个 503 http 状态码...

那么,我怎样才能得到http状态码呢?你们有什么想法吗?

诚挚的问候和感谢!

【问题讨论】:

  • $e->getRequest()->getBody()->getContents() 返回 null 并且 $e->getCode() 返回 0 尽管网站肯定会返回 503 错误。
  • 尝试捕捉ServerExceptionBadResponseException 而不是RequestException
  • 为什么?但是如果不是ServerExceptionBadResponseException 会发生什么?那我就不能捕捉到其他异常了?
  • 如果你捕捉到一个ServerException,你捕捉到一个 5xx,如果代码执行进入那里,Guzzle 已经收到一个 5xx。如果您发现 RequestException 也包含网络错误。如果代码执行在RequestException上进入但在ServerException上没有进入则意味着对于Guzzle来说不是5xx错误而是网络错误。

标签: php laravel exception-handling guzzle http-status-codes


【解决方案1】:

如果你捕获了一个 ServerException,你就是捕获了一个 5xx,如果代码执行进入那里,Guzzle 收到了一个 5xx。如果您也捕获了包含网络错误的 RequestException。如果代码执行在RequestException上进入但在ServerException上没有进入则意味着对于Guzzle来说不是5xx错误而是网络错误。

【讨论】:

    【解决方案2】:

    $errorstatuscode=$exception->状态;

    //从异常对象中获取错误代码

    【讨论】:

      猜你喜欢
      • 2016-06-24
      • 1970-01-01
      • 2017-11-15
      • 2017-09-05
      • 2015-07-05
      • 1970-01-01
      • 2016-09-13
      • 2018-07-04
      • 2021-11-21
      相关资源
      最近更新 更多