Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added API error separation by their HTTP codes #440

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/Exceptions/APIError.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace OpenAI\Exceptions;

use Psr\Http\Message\RequestInterface;

class APIError extends ErrorException
{
public function __construct(protected readonly RequestInterface $request, array $contents)
{
parent::__construct($contents);
}

public function getRequest(): RequestInterface
{
return $this->request;
}
}
30 changes: 30 additions & 0 deletions src/Exceptions/APIStatusError.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

namespace OpenAI\Exceptions;

use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

class APIStatusError extends APIError
{
protected int $statusCode;
protected ?string $requestId;

public function __construct(RequestInterface $request, protected readonly ResponseInterface $response, array $contents)
{
parent::__construct($request, $contents);

$this->statusCode = $response->getStatusCode();
$this->requestId = $response->getHeader('x-request-id')[0] ?? null;
}

public function getStatusCode(): int
{
return $this->statusCode;
}

public function getRequestId(): ?string
{
return $this->requestId;
}
}
8 changes: 8 additions & 0 deletions src/Exceptions/AuthenticationError.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

namespace OpenAI\Exceptions;

class AuthenticationError extends APIStatusError
{
protected int $statusCode = 401;
}
8 changes: 8 additions & 0 deletions src/Exceptions/BadRequestError.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

namespace OpenAI\Exceptions;

class BadRequestError extends APIStatusError
{
protected int $statusCode = 400;
}
8 changes: 8 additions & 0 deletions src/Exceptions/ConflictError.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

namespace OpenAI\Exceptions;

class ConflictError extends APIStatusError
{
protected int $statusCode = 409;
}
4 changes: 2 additions & 2 deletions src/Exceptions/ErrorException.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@

use Exception;

final class ErrorException extends Exception
class ErrorException extends Exception
{
/**
* Creates a new Exception instance.
*
* @param array{message: string|array<int, string>, type: ?string, code: string|int|null} $contents
*/
public function __construct(private readonly array $contents)
public function __construct(protected readonly array $contents)
{
$message = ($contents['message'] ?: (string) $this->contents['code']) ?: 'Unknown error';

Expand Down
8 changes: 8 additions & 0 deletions src/Exceptions/NotFoundError.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

namespace OpenAI\Exceptions;

class NotFoundError extends APIStatusError
{
protected int $statusCode = 404;
}
8 changes: 8 additions & 0 deletions src/Exceptions/PermissionDeniedError.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

namespace OpenAI\Exceptions;

class PermissionDeniedError extends APIStatusError
{
protected int $statusCode = 403;
}
8 changes: 8 additions & 0 deletions src/Exceptions/RateLimitError.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

namespace OpenAI\Exceptions;

class RateLimitError extends APIStatusError
{
protected int $statusCode = 429;
}
8 changes: 8 additions & 0 deletions src/Exceptions/UnprocessableEntityError.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

namespace OpenAI\Exceptions;

class UnprocessableEntityError extends APIStatusError
{
protected int $statusCode = 422;
}
64 changes: 49 additions & 15 deletions src/Transporters/HttpTransporter.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,15 @@
use JsonException;
use OpenAI\Contracts\TransporterContract;
use OpenAI\Enums\Transporter\ContentType;
use OpenAI\Exceptions\AuthenticationError;
use OpenAI\Exceptions\BadRequestError;
use OpenAI\Exceptions\ConflictError;
use OpenAI\Exceptions\ErrorException;
use OpenAI\Exceptions\NotFoundError;
use OpenAI\Exceptions\PermissionDeniedError;
use OpenAI\Exceptions\RateLimitError;
use OpenAI\Exceptions\TransporterException;
use OpenAI\Exceptions\UnprocessableEntityError;
use OpenAI\Exceptions\UnserializableResponse;
use OpenAI\ValueObjects\Transporter\BaseUri;
use OpenAI\ValueObjects\Transporter\Headers;
Expand All @@ -19,6 +26,7 @@
use OpenAI\ValueObjects\Transporter\Response;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

/**
Expand Down Expand Up @@ -46,15 +54,18 @@ public function requestObject(Payload $payload): Response
{
$request = $payload->toRequest($this->baseUri, $this->headers, $this->queryParams);

$response = $this->sendRequest(fn (): \Psr\Http\Message\ResponseInterface => $this->client->sendRequest($request));
$response = $this->sendRequest(
fn (): \Psr\Http\Message\ResponseInterface => $this->client->sendRequest($request),
$request
);

$contents = $response->getBody()->getContents();

if (str_contains($response->getHeaderLine('Content-Type'), ContentType::TEXT_PLAIN->value)) {
return Response::from($contents, $response->getHeaders());
}
Comment on lines 62 to 66

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The work in this PR looks good but I'm seeing intermittent requests failing due to OpenAI API flakeyness (#478). This block needs some of the precautions of throwIfJsonError() otherwise the string response data starts causing TypeError.

Status Code: 404
Content-Type: "text\/plain; charset=utf-8"
Body: "404 page not found\n"


$this->throwIfJsonError($response, $contents);
$this->throwIfJsonError($request, $response, $contents);

try {
/** @var array{error?: array{message: string, type: string, code: string}} $data */
Expand All @@ -73,11 +84,14 @@ public function requestContent(Payload $payload): string
{
$request = $payload->toRequest($this->baseUri, $this->headers, $this->queryParams);

$response = $this->sendRequest(fn (): \Psr\Http\Message\ResponseInterface => $this->client->sendRequest($request));
$response = $this->sendRequest(
fn (): \Psr\Http\Message\ResponseInterface => $this->client->sendRequest($request),
$request
);

$contents = $response->getBody()->getContents();

$this->throwIfJsonError($response, $contents);
$this->throwIfJsonError($request, $response, $contents);

return $contents;
}
Expand All @@ -89,27 +103,38 @@ public function requestStream(Payload $payload): ResponseInterface
{
$request = $payload->toRequest($this->baseUri, $this->headers, $this->queryParams);

$response = $this->sendRequest(fn () => ($this->streamHandler)($request));
$response = $this->sendRequest(fn () => ($this->streamHandler)($request), $request);

$this->throwIfJsonError($response, $response);
$this->throwIfJsonError($request, $response, $response);

return $response;
}

private function sendRequest(Closure $callable): ResponseInterface
private function sendRequest(Closure $callable, RequestInterface $request): ResponseInterface
{
try {
return $callable();
} catch (ClientExceptionInterface $clientException) {
if ($clientException instanceof ClientException) {
$this->throwIfJsonError($clientException->getResponse(), $clientException->getResponse()->getBody()->getContents());
$this->throwIfJsonError($request, $clientException->getResponse(), $clientException->getResponse()->getBody()->getContents());
}

throw new TransporterException($clientException);
}
}

private function throwIfJsonError(ResponseInterface $response, string|ResponseInterface $contents): void
/**
* @throws NotFoundError
* @throws RateLimitError
* @throws AuthenticationError
* @throws UnserializableResponse
* @throws ErrorException
* @throws BadRequestError
* @throws UnprocessableEntityError
* @throws ConflictError
* @throws PermissionDeniedError
*/
private function throwIfJsonError(RequestInterface $request, ResponseInterface $response, string|ResponseInterface $contents): void
{
if ($response->getStatusCode() < 400) {
return;
Expand All @@ -124,12 +149,21 @@ private function throwIfJsonError(ResponseInterface $response, string|ResponseIn
}

try {
/** @var array{error?: array{message: string|array<int, string>, type: string, code: string}} $response */
$response = json_decode($contents, true, flags: JSON_THROW_ON_ERROR);

if (isset($response['error'])) {
throw new ErrorException($response['error']);
}
/** @var array{error: array{message: string|array<int, string>, type: string, code: string}} $contentDecoded */
$contentDecoded = json_decode($contents, true, flags: JSON_THROW_ON_ERROR);

$error = $contentDecoded['error'];

throw match ($response->getStatusCode()) {
400 => new BadRequestError($request, $response, $error),
401 => new AuthenticationError($request, $response, $error),
403 => new PermissionDeniedError($request, $response, $error),
404 => new NotFoundError($request, $response, $error),
409 => new ConflictError($request, $response, $error),
422 => new UnprocessableEntityError($request, $response, $error),
429 => new RateLimitError($request, $response, $error),
default => new ErrorException($contentDecoded['error']),
};
} catch (JsonException $jsonException) {
throw new UnserializableResponse($jsonException);
}
Expand Down
Loading