Skip to content

Commit

Permalink
Merge pull request #487 from GuidoBelluomo/feature/http-status-in-errors
Browse files Browse the repository at this point in the history
HTTP status in ErrorException
  • Loading branch information
gehrisandro authored Nov 12, 2024
2 parents 04c08f2 + 2a3df38 commit 2e62342
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 4 deletions.
12 changes: 11 additions & 1 deletion src/Exceptions/ErrorException.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ final class ErrorException extends Exception
*
* @param array{message: string|array<int, string>, type: ?string, code: string|int|null} $contents
*/
public function __construct(private readonly array $contents)
public function __construct(private readonly array $contents, private readonly int $statusCode)
{
$message = ($contents['message'] ?: (string) $this->contents['code']) ?: 'Unknown error';

Expand All @@ -24,6 +24,16 @@ public function __construct(private readonly array $contents)
parent::__construct($message);
}

/**
* Returns the HTTP status code.
*
* **Note: For streamed requests it might be 200 even in case of an error.**
*/
public function getStatusCode(): int
{
return $this->statusCode;
}

/**
* Returns the error message.
*/
Expand Down
2 changes: 1 addition & 1 deletion src/Responses/StreamResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -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']);
throw new ErrorException($response['error'], $this->response->getStatusCode());
}

if ($event !== null) {
Expand Down
4 changes: 3 additions & 1 deletion src/Transporters/HttpTransporter.php
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,8 @@ private function throwIfJsonError(ResponseInterface $response, string|ResponseIn
return;
}

$statusCode = $response->getStatusCode();

if ($contents instanceof ResponseInterface) {
$contents = $contents->getBody()->getContents();
}
Expand All @@ -128,7 +130,7 @@ private function throwIfJsonError(ResponseInterface $response, string|ResponseIn
$response = json_decode($contents, true, flags: JSON_THROW_ON_ERROR);

if (isset($response['error'])) {
throw new ErrorException($response['error']);
throw new ErrorException($response['error'], $statusCode);
}
} catch (JsonException $jsonException) {
throw new UnserializableResponse($jsonException);
Expand Down
2 changes: 1 addition & 1 deletion tests/Testing/ClientFake.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
'message' => 'The model `gpt-1` does not exist',
'type' => 'invalid_request_error',
'code' => null,
]),
], 404),
]);

$fake->completions()->create([
Expand Down

0 comments on commit 2e62342

Please sign in to comment.