Error Handling in Async Code
What specialized error handling is implemented?
class RateLimiter {
constructor(maxAttempts, timeWindow) {
this.attempts = new Map();
this.maxAttempts = maxAttempts;
this.timeWindow = timeWindow;
}
async handle(operation, key) {
const now = Date.now();
const attempts = this.attempts.get(key) || [];
const recentAttempts = attempts.filter(time => now - time < this.timeWindow);
if (recentAttempts.length >= this.maxAttempts) {
throw new Error(`Rate limit exceeded for ${key}`);
}
recentAttempts.push(now);
this.attempts.set(key, recentAttempts);
try {
return await operation();
} catch (error) {
if (error.status === 429) { // Too Many Requests
throw new Error(`Service rate limit exceeded for ${key}`);
}
throw error;
}
}
}