我正在使用:
请求网络服务 use GuzzleHttpClient;
use GuzzleHttpExceptionConnectException;
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_decode
期间失败?您可以检查请求返回的状态代码。
,甚至代码未能通过您指示的行失败,但是例外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());
}