从食尸鬼中捕获异常

Sur*_*raj 4 php exception-handling guzzle laravel-5

我正在使用laravel,并且已经设置了抽象类方法来从正在调用的各种API中获得响应。但是,如果API网址不可访问,则会引发异常。我知道我想念什么。任何帮助对我来说都是很好的。

$offers = [];
    try {
      $appUrl = parse_url($this->apiUrl);

      // Call Api using Guzzle
      $client = new Client('' . $appUrl['scheme'] . '://' . $appUrl['host'] . '' . $appUrl['path']);

      if ($appUrl['scheme'] == 'https') //If https then disable ssl certificate
        $client->setDefaultOption('verify', false);

      $request = $client->get('?' . $appUrl['query']);
      $response = $request->send();
      if ($response->getStatusCode() == 200) {
        $offers = json_decode($response->getBody(), true);
      }
    } catch (ClientErrorResponseException $e) {
      Log::info("Client error :" . $e->getResponse()->getBody(true));
    } catch (ServerErrorResponseException $e) {
      Log::info("Server error" . $e->getResponse()->getBody(true));
    } catch (BadResponseException $e) {
      Log::info("BadResponse error" . $e->getResponse()->getBody(true));
    } catch (\Exception $e) {
      Log::info("Err" . $e->getMessage());
    }

    return $offers;
Run Code Online (Sandbox Code Playgroud)

小智 5

您应该使用选项设置guzzehttp客户端,'http_errors' => false, 示例代码应如下所示:document:guzzlehttp客户端HTTP错误选项说明

设置为false可禁用对HTTP协议错误(即4xx和5xx响应)的抛出异常。遇到HTTP协议错误时,默认情况下会引发异常。

$client->request('GET', '/status/500');
// Throws a GuzzleHttp\Exception\ServerException

$res = $client->request('GET', '/status/500', ['http_errors' => false]);
echo $res->getStatusCode();
// 500





$this->client = new Client([
    'cookies' => true,
    'headers' => $header_params,
    'base_uri' => $this->base_url,
    'http_errors' => false
]);

$response = $this->client->request('GET', '/');
if ($code = $response->getStatusCode() == 200) {
   try {
       // do danger dom things in here
   }catch (/Exception $e){
      //catch
   }

}
Run Code Online (Sandbox Code Playgroud)