diff --git a/lib/internal/errors.js b/lib/internal/errors.js index 9cc731e99fb3af..50d1cd3fb53b2c 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -12,6 +12,7 @@ const kCode = Symbol('code'); const messages = new Map(); +const codes = {}; var green = ''; var red = ''; @@ -194,6 +195,54 @@ function createErrDiff(actual, expected, operator) { return `${msg}${skipped ? skippedMsg : ''}\n${res}${other}${end}`; } +function makeNodeErrorWithCode(Base, key) { + return class NodeError extends Base { + constructor(...args) { + super(message(key, args)); + } + + get name() { + return `${super.name} [${key}]`; + } + + set name(value) { + defineProperty(this, 'name', { + configurable: true, + enumerable: true, + value, + writable: true + }); + } + + get code() { + return key; + } + + set code(value) { + defineProperty(this, 'code', { + configurable: true, + enumerable: true, + value, + writable: true + }); + } + }; +} + +// Utility function for registering the error codes. Only used here. Exported +// *only* to allow for testing. +function E(sym, val, def, ...otherClasses) { + messages.set(sym, val); + if (def === undefined) return; + def = makeNodeErrorWithCode(def, sym); + if (otherClasses.length !== 0) { + otherClasses.forEach((clazz) => { + def[clazz.name] = makeNodeErrorWithCode(clazz, sym); + }); + } + codes[sym] = def; +} + class AssertionError extends Error { constructor(options) { if (typeof options !== 'object' || options === null) { @@ -296,12 +345,6 @@ function message(key, args) { return String(fmt.apply(null, args)); } -// Utility function for registering the error codes. Only used here. Exported -// *only* to allow for testing. -function E(sym, val) { - messages.set(sym, typeof val === 'function' ? val : String(val)); -} - /** * This used to be util._errnoException(). * @@ -412,6 +455,7 @@ module.exports = exports = { RangeError: makeNodeError(RangeError), URIError: makeNodeError(URIError), AssertionError, + codes, E // This is exported only to facilitate testing. };