Error Handling in Async Code
What resilience pattern is implemented here?
class CircuitBreaker {
constructor(operation, failureThreshold = 5, resetTimeout = 60000) {
this.operation = operation;
this.failureThreshold = failureThreshold;
this.resetTimeout = resetTimeout;
this.failures = 0;
this.lastFailureTime = null;
this.state = 'CLOSED';
}
async execute(...args) {
if (this.state === 'OPEN') {
if (Date.now() - this.lastFailureTime >= this.resetTimeout) {
this.state = 'HALF_OPEN';
} else {
throw new Error('Circuit breaker is OPEN');
}
}
try {
const result = await this.operation(...args);
this.reset();
return result;
} catch (error) {
this.failures++;
this.lastFailureTime = Date.now();
if (this.failures >= this.failureThreshold) {
this.state = 'OPEN';
}
throw error;
}
}
reset() {
this.failures = 0;
this.state = 'CLOSED';
}
}