Handling API errors well
Owner, AdminLast checked 25 November 20262 min readArticle ID:
developers-handling-errorsOn this page
Branch on error.code, retry only what is worth retrying, and reuse the idempotency key when you do.
Every failed call returns the same envelope, so one small wrapper can handle all of them. See API errors for every code.
The rules
- Branch on
error.code. It's stable.error.messageis for people and can change. - Retry only what can succeed later:
409,429,500and503, with exponential backoff and a little randomness (jitter). On429, wait theRetry-Afterseconds first. - On
401, get a fresh token and retry once. If it still fails, the app was revoked or its secret changed. - Don't retry
403,404or422. The request is wrong, or the app lacks a scope. Fix it instead. - Retry writes with the same
Idempotency-Key, so a retry never does the work twice. A new key is for a new write. See Safe retries with idempotency keys. - Never log the secret or the token. Log
error.code, the status and the path.
A small wrapper
In the example, SKEDULER_API is your Skeduler API address. Contact Skeduler support if you don't have it.
async function call(path, { method = "GET", body, key } = {}) {
const idempotencyKey = method === "GET" ? undefined : key ?? crypto.randomUUID(); // chosen once per write
let refreshed = false;
for (let attempt = 0; attempt < 5; attempt++) {
const res = await fetch(`${process.env.SKEDULER_API}/api/v1${path}`, {
method,
headers: {
Authorization: `Bearer ${await getToken()}`,
"Content-Type": "application/json",
...(idempotencyKey && { "Idempotency-Key": idempotencyKey }),
},
body: body && JSON.stringify(body),
});
if (res.ok) return res.json();
const { error } = await res.json().catch(() => ({ error: { code: "server_error" } }));
if (res.status === 401 && !refreshed) { refreshed = true; await getToken({ force: true }); continue; }
if ([409, 429, 500, 503].includes(res.status)) {
const wait = Number(res.headers.get("Retry-After")) * 1000 || Math.min(30000, 500 * 2 ** attempt) * (0.5 + Math.random());
await new Promise((r) => setTimeout(r, wait));
continue;
}
throw Object.assign(new Error(error.message), { status: res.status, code: error.code, fields: error.fields });
}
throw new Error("Gave up after 5 attempts");
}
getToken() returns a cached token and asks for a new one shortly before it expires. See How long does an access token last?.
Showing a problem to a person
For 422 validation_failed, error.fields has a message for each field you can show next to the right box. See My request fails with validation_failed. A 500 is always server_error: tell the person something went wrong on Skeduler's side and that you'll try again, rather than showing a raw response.