UNPKG

error3

Version:

Error3 is proper JS error implementation. It supports error codes, message formatting (e.g. i18n) and nested errors.

62 lines (59 loc) 1.64 kB
'use strict'; class Error3 extends Error { constructor(details, errors) { super(); this.code = 0; this.name = this.constructor.name; if (details) { if (isObject(details) && isPlainObject(details)) { this.details = Object.assign({}, details); } else { throw new Error('Details should be a plain Object instance or undefined'); } } else { this.details = {}; } if (errors) { if (isErrors(errors)) { this.errors = errors; } else { throw new Error('Errors should be an array of errors'); } } else { this.errors = []; } this.message = this.format(details, errors); } valueOf() { return { code: this.code, message: this.message, details: this.details, errors: this.errors.map((error) => error.valueOf()), }; } toString() { const { name, code, message } = this; return `${name}: [#${code}] ${message}`; } toJSON() { return this.valueOf(); } } function isErrors(value) { return (Array.isArray(value) && value.every((item) => isErrorObject(item))); } function isObject(value) { return value !== null && typeof value === 'object'; } function isErrorObject(value) { return isObject(value) && value instanceof Error; } function isPlainObject(value) { return value.constructor.toString() === Object.toString(); } module.exports = Error3;