Skip to content
Support

Handling API errors well

Owner, AdminLast checked 25 November 20262 min readArticle ID: developers-handling-errors
On 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

  1. Branch on error.code. It's stable. error.message is for people and can change.
  2. Retry only what can succeed later: 409, 429, 500 and 503, with exponential backoff and a little randomness (jitter). On 429, wait the Retry-After seconds first.
  3. On 401, get a fresh token and retry once. If it still fails, the app was revoked or its secret changed.
  4. Don't retry 403, 404 or 422. The request is wrong, or the app lacks a scope. Fix it instead.
  5. 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.
  6. 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.

In this section