Skip to content

Commit 055a60e

Browse files
committed
Handle HTTP errors in streaming requests
1 parent d56e712 commit 055a60e

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

src/Client.php

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,12 @@
2929

3030
use function curl_close;
3131
use function curl_exec;
32+
use function curl_getinfo;
3233
use function curl_init;
3334
use function curl_setopt;
3435
use function extension_loaded;
3536
use function json_decode;
37+
use function sprintf;
3638

3739
class Client implements GeminiClientInterface
3840
{
@@ -103,6 +105,21 @@ public function generateContentStream(
103105
static fn (array $arr) => $callback(GenerateContentResponse::fromArray($arr)),
104106
);
105107

108+
$writeFunction = static function (CurlHandle $ch, string $str) use ($request, $parser): int {
109+
$responseCode = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
110+
111+
return $responseCode === 200
112+
? $parser->consume($str)
113+
: throw new RuntimeException(
114+
sprintf(
115+
'Gemini API operation failed: operation=%s, status_code=%d, response=%s',
116+
$request->getOperation(),
117+
$responseCode,
118+
$str,
119+
),
120+
);
121+
};
122+
106123
$ch = curl_init("{$this->baseUrl}/v1/{$request->getOperation()}");
107124

108125
if ($ch === false) {
@@ -115,11 +132,7 @@ public function generateContentStream(
115132
'Content-type: application/json',
116133
self::API_KEY_HEADER_NAME . ": {$this->apiKey}",
117134
]);
118-
curl_setopt(
119-
$ch,
120-
CURLOPT_WRITEFUNCTION,
121-
static fn (CurlHandle $ch, string $str): int => $parser->consume($str),
122-
);
135+
curl_setopt($ch, CURLOPT_WRITEFUNCTION, $writeFunction);
123136
curl_exec($ch);
124137
curl_close($ch);
125138
}

0 commit comments

Comments
 (0)