diff --git a/lib/internal/errors.js b/lib/internal/errors.js index 92e1efbf2fb4b8..ea72ea714d8518 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -13,6 +13,7 @@ const kCode = Symbol('code'); const kInfo = Symbol('info'); const messages = new Map(); +const codes = {}; var green = ''; var red = ''; @@ -86,6 +87,54 @@ function makeNodeError(Base) { }; } +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; +} + function lazyBuffer() { if (buffer === undefined) buffer = require('buffer').Buffer; @@ -367,12 +416,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 creates an error compatible with errors produced in the C++ * function UVException using a context object with data assembled in C++. @@ -523,6 +566,7 @@ module.exports = exports = { URIError: makeNodeError(URIError), AssertionError, SystemError, + codes, E, // This is exported only to facilitate testing. errorCache: new Map() // This is in here only to facilitate testing. };