2016-07-27 19 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文件:) –