smart-saga-pattern
Version:
A library implementing the Saga pattern for microservice architecture
52 lines (51 loc) • 1.66 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ErrorHandler = void 0;
/**
* Handles errors in the Saga system
*/
class ErrorHandler {
/**
* Creates a new ErrorHandler
* @param options Error handler options
*/
constructor(options = {}) {
this.logger = options.logger;
this.retryCount = options.retryCount || 3;
this.retryDelay = options.retryDelay || 1000;
}
/**
* Executes a function with retry logic
* @param fn Function to execute
* @param context Context for error logging
*/
async executeWithRetry(fn, context = {}) {
let lastError;
for (let attempt = 1; attempt <= this.retryCount + 1; attempt++) {
try {
return await fn();
}
catch (error) {
lastError = error instanceof Error ? error : new Error(String(error));
if (this.logger) {
this.logger.warn(`Operation failed (attempt ${attempt}/${this.retryCount + 1})`, { ...context, error: lastError.message });
}
if (attempt <= this.retryCount) {
await this.delay(this.retryDelay * attempt);
}
}
}
if (this.logger) {
this.logger.error(`Operation failed after ${this.retryCount + 1} attempts`, lastError, context);
}
throw lastError;
}
/**
* Creates a delay
* @param ms Milliseconds to delay
*/
delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
exports.ErrorHandler = ErrorHandler;