@remcostoeten/fync
Version:
A unified TypeScript library for easy access to popular APIs (GitHub, Spotify, GitLab, etc.)
79 lines • 2.18 kB
JavaScript
/**
* Base class for all errors
*/
export class BaseError extends Error {
constructor(info) {
super(info.message);
this.info = info;
this.name = "BaseError";
Object.setPrototypeOf(this, new.target.prototype);
}
}
/**
* Centralized error utility class for building and managing errors
*/
export class ErrorUtil {
/**
* Register error transformer
*/
static registerTransformer(transformer) {
this.transformers.push(transformer);
}
/**
* Register error handler
*/
static registerHandler(handler) {
this.handlers.push(handler);
}
/**
* Register recovery strategy
*/
static registerRecovery(recovery) {
this.recoveries.push(recovery);
}
/**
* Generate a BaseError from unknown error
*/
static createError(error, context) {
for (const transformer of this.transformers) {
const transformed = transformer(error);
if (transformed) {
return new BaseError({ ...transformed, context: { ...transformed.context, ...context } });
}
}
return new BaseError({
code: "UNKNOWN_ERROR",
category: "unknown",
severity: "high",
message: `Unhandled error: ${error}`,
service: context.service || "core",
context: { ...context, timestamp: new Date(), service: context.service || "core" },
isRetryable: false,
});
}
/**
* Handle the provided error
*/
static async handle(error) {
for (const handler of this.handlers) {
await handler(error.info);
}
}
/**
* Attempt to recover from an error
*/
static async recover(error) {
for (const recovery of this.recoveries) {
const result = await recovery(error.info);
if (result !== null && result !== undefined) {
return result;
}
}
return null;
}
}
ErrorUtil.transformers = [];
ErrorUtil.handlers = [];
ErrorUtil.recoveries = [];
ErrorUtil.initialized = false;
//# sourceMappingURL=index.js.map