UNPKG

cmpstr

Version:

CmpStr is a lightweight, fast and well performing package for calculating string similarity

104 lines (102 loc) 2.65 kB
// CmpStr v3.2.2 build-bb61120-260311 by Paul Köhler @komed3 / MIT License class CmpStrError extends Error { code; meta; cause; when = new Date().toISOString(); constructor(code, message, meta, cause) { super(message); this.name = this.constructor.name; this.code = code; this.meta = meta; this.cause = cause; if (typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, this.constructor); } } toJSON() { return { name: this.name, code: this.code, message: this.message, meta: this.meta, when: this.when, cause: this.cause instanceof Error ? { name: this.cause.name, message: this.cause.message, stack: this.cause.stack } : this.cause }; } toString(stack = false) { const parts = [`${this.name} [${this.code}]`, this.message]; if (this.meta && Object.keys(this.meta).length) { try { parts.push(JSON.stringify(this.meta)); } catch {} } return ( parts.join(' - ') + (stack && this.stack ? `\nStack Trace:\n${this.stack}` : '') ); } } class CmpStrValidationError extends CmpStrError { constructor(message, meta, cause) { super('E_VALIDATION', message, meta, cause); } } class CmpStrNotFoundError extends CmpStrError { constructor(message, meta, cause) { super('E_NOT_FOUND', message, meta, cause); } } class CmpStrUsageError extends CmpStrError { constructor(message, meta, cause) { super('E_USAGE', message, meta, cause); } } class CmpStrInternalError extends CmpStrError { constructor(message, meta, cause) { super('E_INTERNAL', message, meta, cause); } } class ErrorUtil { static assert(condition, message, meta) { if (!condition) throw new CmpStrUsageError(message, meta); } static create(err, message, meta) { if (err instanceof CmpStrError) throw err; throw new CmpStrInternalError(message, meta, err); } static format(err) { if (err instanceof CmpStrError) return err.toString(); if (err instanceof Error) return `${err.name}: ${err.message}`; return String(err); } static wrap(fn, message, meta) { try { return fn(); } catch (err) { throw new CmpStrInternalError(message, meta, err); } } static async wrapAsync(fn, message, meta) { try { return await fn(); } catch (err) { throw new CmpStrInternalError(message, meta, err); } } } export { CmpStrError, CmpStrInternalError, CmpStrNotFoundError, CmpStrUsageError, CmpStrValidationError, ErrorUtil };