UNPKG

@opra/common

Version:
72 lines (71 loc) 2.17 kB
import { omitUndefined } from '@jsopen/objects'; import { i18n } from '../i18n/index.js'; /** * Defines the base Opra exception, which is handled by the default Exceptions Handler. */ export class OpraException extends Error { cause; severity = 'error'; system; code; details; constructor(issue, cause) { super('Unknown error'); cause = cause || (issue instanceof Error ? issue : undefined); if (issue instanceof Error) cause = issue; // noinspection SuspiciousTypeOfGuard if (cause && cause instanceof Error) { this.cause = cause; if (cause.stack) this.stack = cause.stack; } if (typeof issue === 'string') this.initString(issue); else if (issue instanceof Error) this.initError(issue); else this.init(issue); this.message = this.message || this.constructor.name; } toString() { return i18n.deep(this.message); } toJSON() { return omitUndefined({ message: this.message, severity: this.severity, system: this.system, code: this.code, details: this.details, stack: this.stack, }, true); } init(issue) { this.message = issue?.message || this.constructor.name; this.severity = issue?.severity || 'error'; if (issue) { this.system = issue.system; this.code = issue.code; this.details = issue.details; } } initString(issue) { this.init({ message: String(issue || '') || this.constructor.name, severity: 'error', code: this.constructor.name, }); } initError(issue) { const env = process.env.NODE_ENV; this.init({ message: issue.message, severity: issue.severity || 'error', code: issue.code || issue.constructor.name, stack: env === 'dev' || env === 'development' || env === 'test' ? issue.stack : undefined, }); } }