2017-02-27 92 views
0

我使用请求Web服务:今天如何处理错误500当请求一个远程服务器与guzzle?

use GuzzleHttp\Client; 
use GuzzleHttp\Exception\ConnectException; 
    try { 
    $client = new Client(); 
    $response = $client->request('GET', $url); //it crashes at this line 
    $content = json_decode($response->getBody(), true); 

} 
catch (ConnectException $e) { 
    \Drupal::logger('amu_hal')->error('incorrect_url'.$url); 
} 

远程服务器返回错误500

如何修改我的代码不会崩溃我的网站,当它发生?

回答

1

我假设通过遥远的服务器,你的意思是一个需要很长时间才能连接的服务器。您可以指定请求的超时时间。

或者服务器可能返回错误500,并在json_decode期间失败?您可以检查请求返回的状态代码。

甚至可能是代码没有显示您指定的行,但ConnectException异常未被捕获?尝试使用Exception作为一个全面的调试这种情况。

而不是直接使用Guzzle,我建议您使用Drupal包装(它使用下面的Guzzle)。

$client = Drupal::httpClient(); 
$request = $client->get($uri, ['connect_timeout' => 5]); 
if ($request->getStatusCode() === 200) { 
    echo 'Connection Success'; 
} else { 
    echo sprintf('Error %d occurred', $request->getStatusCode()); 
} 
相关问题