SDK Toolbox docs
Errors
PHP ^8.316 pages
Docs for v0.1.0, from GitHub.
Pages in these docs
Every exception the toolbox throws implements SdkException, so an SDK’s callers can catch one type for everything.
| Exception | When |
|---|---|
HttpException and its subclasses | The API answered 4xx or 5xx |
TransportException | No response at all: DNS, TLS, refused connection, timeout |
InvalidResponseException | A response that isn’t the JSON a request expected |
HydrationException | JSON that doesn’t fit the class you mapped it to |
InvalidRequestException, UnsafeUriException | A request that can’t be built safely. Nothing was sent |
NoHttpClientException | A connector was built without a client or factories, and none is installed (Getting started) |
RateLimitExceededException | The throttle refused to send (Reliability) |
OAuthException | The authorisation server said no (Authentication) |
HTTP errors
send() throws for any 4xx or 5xx. The class depends on the status:
| Status | Exception |
|---|---|
| 400 | BadRequestException |
| 401 | UnauthorizedException |
| 403 | ForbiddenException |
| 404 | NotFoundException |
| 409 | ConflictException |
| 410 | GoneException |
| 412 | PreconditionFailedException |
| 422 | UnprocessableContentException |
| 428 | PreconditionRequiredException |
| 429 | TooManyRequestsException |
| other 4xx | ClientException |
| 5xx | ServerException |
Every one of them carries:
$e->status;$e->response: the PSR-7 response, body and all;$e->request: a redacted snapshot of the request (method, URI, headers), never the request itself, which would carry credentials;$e->problem: the RFC 9457 problem details, when the body had them;$e->retryAfter: seconds fromRetry-After, when the server sent one.
The message names the request and the status, then the problem’s detail or title: GET /v2/projects/prj_9 returned 404 Not Found: No project prj_9.
Problem details
APIs that answer errors with application/problem+json (RFC 9457) get them parsed the way the RFC tells a client to:
try { $acme->projects()->create('Docs');} catch (UnprocessableContentException $e) { $e->problem?->type; // 'https://api.acme.test/problems/validation' $e->problem?->extension('errors'); // ['name' => ['Required.']]}typeis the problem’s identifier. A relative one is resolved against the request URI (without its query, so a key can’t leak into it). It’s never fetched.- Mistyped members are ignored, as section 3.1 says: a
statusof"404"is dropped, not trusted. - Everything else is an extension, read with
extension().
Don’t branch on title or detail. They’re prose for humans, and they change.
Mapping an API’s own problems
An ExceptionMapper decides which exception a response becomes. ProblemTypes maps problem types to your SDK’s exceptions, and falls back to the status mapping for anything else:
parent::__construct( baseUri: 'https://api.acme.test', exceptions: new ProblemTypes([ 'https://api.acme.test/problems/out-of-credit' => OutOfCredit::class, ]),);final class OutOfCredit extends ClientException{ public function balance(): int { $balance = $this->problem?->extension('balance');
return is_int($balance) ? $balance : 0; }}The constructor of HttpException is final, so the mapper can always build your class the same way. To change the message, override describe():
protected function describe(Response $response, ?ProblemDetails $problem): string{ return $problem?->title ?? 'Acme returned an error.';}APIs without RFC 9457
Most APIs answer errors in a shape of their own: {"error": "..."}, an errors array, a code and a tag. For the common case, a flat JSON object, name the fields and let StatusExceptions::fromFields() read them:
// Resend: {"statusCode": 422, "name": "validation_error", "message": "..."}exceptions: StatusExceptions::fromFields(title: 'name', detail: 'message'),
// Todoist: {"error": "...", "error_code": 477, "error_extra": {"event_id": "..."}}exceptions: StatusExceptions::fromFields(title: 'error', extensions: [ 'code' => 'error_code', 'event_id' => 'error_extra.event_id',]),Paths are dotted, as $response->get() reads them. title is the field that marks a body as one of the API’s errors: if it’s missing, isn’t a string, or the body isn’t JSON, nothing is read and the RFC 9457 problem is used if there is one. detail and type are kept when they’re strings, and each extension is kept as it was sent, or null. Both SDKs built on the toolbox against real APIs had written this by hand, mapper and reader, before it existed.
For anything stranger, such as an errors array to flatten, give StatusExceptions a function that reads the shape into a ProblemDetails, and every status exception carries it, whatever the status:
parent::__construct( baseUri: 'https://api.acme.test', exceptions: new StatusExceptions(problems: function (Response $response): ?ProblemDetails { $body = json_decode($response->body(), true);
if (! is_array($body) || ! is_string($body['error'] ?? null)) { return null; }
return new ProblemDetails( title: $body['error'], status: $response->status(), extensions: ['code' => $body['code'] ?? null], ); }),);A 404 is still a NotFoundException, and $e->problem->title is the API’s own message, which the exception’s message uses too. Put anything else the body holds in extensions, and read it back with $e->problem->extension('code'). When the function returns null, the RFC 9457 problem is used, if the response has one.
To map some of the API’s errors to your own exceptions as well, write an ExceptionMapper and fall back to that StatusExceptions for the rest.
Transport errors
When no response comes back, TransportException wraps the PSR-18 client’s exception, and keeps a masked copy of it as getPrevious().
$e->networkis true for a network failure, as opposed to the client refusing the request itself.- Credentials in the message are masked: HTTP clients often quote the full URL in their error, query string and all.
- So is the previous exception’s.
getPrevious()is aRedactedClientException: the client’s class (in$e->classand at the start of the message), its code, file and line, and its message with credentials masked, and the same for any exception the client’s own wraps. The original isn’t kept, so logs that write out the whole chain, as Laravel’s and Monolog’s do, can’t carry a key from it.
A network failure on a safe request is retried before it’s thrown: see Reliability.