我正在使用 eleventy-fetch 发出请求,如下所示:
let response = await EleventyFetch(url, {
duration: "1h",
type: "json"
});
但是,有时会失败并出现错误:
[url] (429) 的错误响应:请求太多(通过错误)
我知道我的请求太频繁了,所以我想建立指数退避。然而,我最初的尝试并没有成功:
let response;
let attempts = 0;
const maxAttempts = 5;
while (attempts < maxAttempts) {
try {
response = await EleventyFetch(url, {
duration: "1h",
type: "json"
});
break; // If request is successful, exit the loop
} catch (err) {
if (err.response && err.response.status === 429) {
attempts++;
const waitTime = Math.pow(2, attempts) * 1000; // Exponential backoff
console.warn(`Rate limit exceeded. Retrying in ${waitTime / 1000} seconds...`);
await new Promise(resolve => setTimeout(resolve, waitTime));
} else {
throw err; // If it's not a 429 error, rethrow the error
}
}
}
错误仍在抛出,指数退避从未发生。我做错了什么?
您想要寻找
err.cause
,而不是 err.response
。
eleventy-fetch 的 RemoteAssetCache.js 源代码显示了错误产生的位置:
if (!response.ok) {
throw new Error(
`Bad response for ${this.displayUrl} (${response.status}): ${response.statusText}`,
{ cause: response },
);
}
这里,响应作为属性附加到错误中
cause
。
要使指数退避发挥作用,您只需将
err.response
切换为 err.cause
:
let response;
let attempts = 0;
const maxAttempts = 5;
while (attempts < maxAttempts) {
try {
response = await EleventyFetch(url, {
duration: "1h",
type: "json"
});
break; // If request is successful, exit the loop
} catch (err) {
if (err.cause && err.cause.status === 429) {
attempts++;
const waitTime = Math.pow(2, attempts) * 1000; // Exponential backoff
console.warn(`Rate limit exceeded. Retrying in ${waitTime / 1000} seconds...`);
await new Promise(resolve => setTimeout(resolve, waitTime));
} else {
throw err; // If it's not a 429 error, rethrow the error
}
}
}