Error handling 当使用guzzle请求远程服务器时,如何处理错误500?

Error handling 当使用guzzle请求远程服务器时,如何处理错误500?,error-handling,guzzle,drupal-8,Error Handling,Guzzle,Drupal 8,我正在使用以下方式请求Web服务: 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);

我正在使用以下方式请求Web服务:

 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


如何修改我的代码,使其在发生故障时不会崩溃?

我假设远程服务器指的是需要很长时间连接的服务器。您可以为请求指定超时

或者服务器返回了错误500,在
json\u解码过程中失败了?您可以检查请求返回的状态代码

或者甚至可能代码未通过您指示的行,但未捕获异常
ConnectException
?尝试使用
Exception
作为全面调试此情况的工具

我建议您使用Drupal包装(在引擎盖下使用Guzzle),而不是直接使用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());
}