Handling errors
Every client turns a non-2xx response into its language’s idiomatic failure: a
thrown exception in TypeScript, Python, Ruby, PHP, Java and C#, and a returned
error plus *http.Response in Go.
Branch on code, then on status
The API returns RFC 9457 problem documents. The fields that matter, in order of how stable they are:
| Field | Stability |
|---|---|
code |
A contract. Stable forever once published. Branch on this |
status |
Stable. Branch on this when there is no code |
title, detail |
Prose. Written for a human reading a log. Never branch on these |
request_id |
Unique per call. Log this |
Only some conditions carry a code today, insufficient_scope and
business_mode_required among them. Where there is none, the status is what
you have.
Getting at the body
This is where generated clients vary most, and the detail you want is in the response body rather than the exception message.
TypeScript throws a ResponseError carrying the Response; read
err.response.json() for the problem document.
Python raises ApiException with .status and .body; parse .body as
JSON.
Go returns an error and the *http.Response as the second value. Read
the response even when the error is non-nil: that is where the problem
document is, and discarding it with _ is how people end up debugging a
delivery problem from a status code alone.
Ruby, PHP, Java, C# raise an exception exposing the status and the response body in a language-appropriate way.
In every case, capture request_id and put it in your log line. It is the
one value that lets support find your exact call, and failures are precisely
where you cannot get it any other way.
Which failures are worth retrying
| Status | Retry? |
|---|---|
429 |
Yes, after Retry-After |
500, 502, 503, 504 |
Yes, with backoff |
| network timeout, connection reset | Yes |
400, 404, 409, 422 |
No. The request is wrong; retrying repeats it |
401, 403 |
No. Fix the key or its scopes |
Validation happens on the server
The typed models stop you passing a number where a string belongs. They do
not encode the API’s rules: that templateId excludes inline content, that
to plus cc plus bcc is capped at 100, that one of text or html is
required.
Those arrive as 400 at runtime. A request that compiles is not a request
that validates, which is worth knowing before you trust the types to catch a
mistake.