Robust error handling
This wrapper retries only the errors that are safe to retry and logs the request id of every failure.
async function webknx(path, body, attempt = 1) {
const res = await fetch(`https://webknx.com${path}`, {
method: "POST",
headers: { Authorization: `Bearer ${process.env.WEBKNX_SECRET_KEY}`, "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (res.ok) return res;
const { error } = await res.json();
const retryable = [429, 500, 503].includes(res.status);
if (!retryable || attempt >= 5) {
throw Object.assign(new Error(error.message), error);
}
const retryAfter = Number(res.headers.get("Retry-After")) * 1000;
const backoff = retryAfter || 1000 * 2 ** (attempt - 1) * (0.8 + Math.random() * 0.4);
await new Promise((r) => setTimeout(r, backoff));
return webknx(path, body, attempt + 1);
}
Key points:
4xxerrors other than429mean the request itself is wrong; retrying will not help.- Failed requests are never charged, so retries are safe.
- Log
error.request_idso support can find the exact request.