gpt4 book ai didi

php - 从 guzzle 捕获异常

转载 作者:行者123 更新时间:2023-12-03 02:12:16 24 4
gpt4 key购买 nike

我正在使用 laravel,并且我已经设置了抽象类方法来从我调用的各种 API 中获取响应。但如果 API url 无法访问,则会抛出异常。我知道我错过了一些东西。任何帮助对我来说都是很大的。

$offers = [];
try {
$appUrl = parse_url($this->apiUrl);

// Call Api using Guzzle
$client = new Client('' . $appUrl['scheme'] . '://' . $appUrl['host'] . '' . $appUrl['path']);

if ($appUrl['scheme'] == 'https') //If https then disable ssl certificate
$client->setDefaultOption('verify', false);

$request = $client->get('?' . $appUrl['query']);
$response = $request->send();
if ($response->getStatusCode() == 200) {
$offers = json_decode($response->getBody(), true);
}
} catch (ClientErrorResponseException $e) {
Log::info("Client error :" . $e->getResponse()->getBody(true));
} catch (ServerErrorResponseException $e) {
Log::info("Server error" . $e->getResponse()->getBody(true));
} catch (BadResponseException $e) {
Log::info("BadResponse error" . $e->getResponse()->getBody(true));
} catch (\Exception $e) {
Log::info("Err" . $e->getMessage());
}

return $offers;

最佳答案

您应该使用选项 'http_errors' => false, 设置 guzzehttp 客户端示例代码应该是这样的,document:guzzlehttp client http-error option explain

Set to false to disable throwing exceptions on an HTTP protocol errors (i.e., 4xx and 5xx responses). Exceptions are thrown by default when HTTP protocol errors are encountered.

$client->request('GET', '/status/500');
// Throws a GuzzleHttp\Exception\ServerException

$res = $client->request('GET', '/status/500', ['http_errors' => false]);
echo $res->getStatusCode();
// 500





$this->client = new Client([
'cookies' => true,
'headers' => $header_params,
'base_uri' => $this->base_url,
'http_errors' => false
]);

$response = $this->client->request('GET', '/');
if ($code = $response->getStatusCode() == 200) {
try {
// do danger dom things in here
}catch (/Exception $e){
//catch
}

}

关于php - 从 guzzle 捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38094743/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com