2016-07-27 92 views
1

因此,我正在与guzzleHttp一起工作,我可以得到我所做的回应并捕获错误。如何检查使用GuzzleHTTP时端点是否工作

我遇到的唯一问题是,如果基本URI是错误的,整个脚本将失败......我该如何做一些检查以确保端点实际上运行?

$client = new GuzzleHttp\Client(['base_uri' => $url]); 
+0

您可以检查'$ url'存在,看看这个http://stackoverflow.com/questions/26555661/what-is-the-best-way-to-use-guzzle-检查是否存在远程文件 –

+0

非常感谢! – Jamie

+0

如何利用Psr7响应中返回的响应代码? '$响应 - > getStatusCode()' –

回答

0

您的查询可能有许多问题,而不仅仅是端点关闭。您的服务器上的网络接口可以在查询的时刻向下,DNS可以关闭,到主机的路由可能不可用,连接超时等。

因此,您绝对应该为许多问题做好准备。我通常会捕获一般RequestException并执行某些操作(日志记录,应用程序特定处理),如果我应该以不同的方式处理它们,则还会捕获特定的异常。

此外,还有许多现有的错误处理模式(和解决方案)。例如,通常重试查询是端点不可用。

$stack = HandlerStack::create(); 
$stack->push(Middleware::retry(
    function (
     $retries, 
     RequestInterface $request, 
     ResponseInterface $response = null, 
     RequestException $exception = null 
    ) { 
     // Don't retry if we have run out of retries. 
     if ($retries >= 5) { 
      return false; 
     } 

     $shouldRetry = false; 
     // Retry connection exceptions. 
     if ($exception instanceof ConnectException) { 
      $shouldRetry = true; 
     } 
     if ($response) { 
      // Retry on server errors. 
      if ($response->getStatusCode() >= 500) { 
       $shouldRetry = true; 
      } 
     } 

     // Log if we are retrying. 
     if ($shouldRetry) { 
      $this->logger->debug(
       sprintf(
        'Retrying %s %s %s/5, %s', 
        $request->getMethod(), 
        $request->getUri(), 
        $retries + 1, 
        $response ? 'status code: ' . $response->getStatusCode() : 
         $exception->getMessage() 
       ) 
      ); 
     } 

     return $shouldRetry; 
    } 
)); 

$client = new Client([ 
    'handler' => $stack, 
    'connect_timeout' => 60.0, // Seconds. 
    'timeout' => 1800.0, // Seconds. 
]); 
+0

嗨,我现在越来越:遇到 一个PHP错误 严重性:4096 消息:传递给:: myController的参数{3}关闭()必须是一个实例ResponseInterface的,GuzzleHttp \ PSR7 \响应的情况下给出 文件名:控制器/ mycontroller.php 行号:72个 任何想法? – Jamie

+0

只需导入界面。 我没有包含'使用GuzzleHttp \ Psr7 \ ResponseInterface',因为它只有一个小片段,而不是整个PHP文件:) –