diff --git a/src/Exceptions/ErrorException.php b/src/Exceptions/ErrorException.php index a72a8666..5f28481b 100644 --- a/src/Exceptions/ErrorException.php +++ b/src/Exceptions/ErrorException.php @@ -5,16 +5,20 @@ namespace OpenAI\Exceptions; use Exception; +use Psr\Http\Message\ResponseInterface; final class ErrorException extends Exception { + private readonly int $statusCode; + /** * Creates a new Exception instance. * * @param array{message: string|array, type: ?string, code: string|int|null} $contents */ - public function __construct(private readonly array $contents, private readonly int $statusCode) + public function __construct(private readonly array $contents, public readonly ResponseInterface $response) { + $this->statusCode = $response->getStatusCode(); $message = ($contents['message'] ?: (string) $this->contents['code']) ?: 'Unknown error'; if (is_array($message)) { diff --git a/src/Responses/StreamResponse.php b/src/Responses/StreamResponse.php index c50bc65f..ddfc0cae 100644 --- a/src/Responses/StreamResponse.php +++ b/src/Responses/StreamResponse.php @@ -57,7 +57,7 @@ public function getIterator(): Generator $response = json_decode($data, true, flags: JSON_THROW_ON_ERROR); if (isset($response['error'])) { - throw new ErrorException($response['error'], $this->response->getStatusCode()); + throw new ErrorException($response['error'], $this->response); } if (isset($response['type']) && $response['type'] === 'ping') { diff --git a/src/Transporters/HttpTransporter.php b/src/Transporters/HttpTransporter.php index e9573479..121a4805 100644 --- a/src/Transporters/HttpTransporter.php +++ b/src/Transporters/HttpTransporter.php @@ -143,18 +143,16 @@ private function throwIfJsonError(ResponseInterface $response, string|ResponseIn return; } - $statusCode = $response->getStatusCode(); - if ($contents instanceof ResponseInterface) { $contents = (string) $contents->getBody(); } try { - /** @var array{error?: array{message: string|array, type: string, code: string}} $response */ - $response = json_decode($contents, true, flags: JSON_THROW_ON_ERROR); + /** @var array{error?: array{message: string|array, type: string, code: string}} $data */ + $data = json_decode($contents, true, flags: JSON_THROW_ON_ERROR); - if (isset($response['error'])) { - throw new ErrorException($response['error'], $statusCode); + if (isset($data['error'])) { + throw new ErrorException($data['error'], $response); } } catch (JsonException $jsonException) { throw new UnserializableResponse($jsonException, $response); diff --git a/tests/Testing/ClientFake.php b/tests/Testing/ClientFake.php index 3e4d5fa5..6f09fb1f 100644 --- a/tests/Testing/ClientFake.php +++ b/tests/Testing/ClientFake.php @@ -54,7 +54,7 @@ 'message' => 'The model `gpt-1` does not exist', 'type' => 'invalid_request_error', 'code' => null, - ], 404), + ], new \GuzzleHttp\Psr7\Response(404)), ]); $fake->completions()->create([