diff --git a/src/errors.js b/src/errors.js index 35f18a6f0..f971e2a85 100644 --- a/src/errors.js +++ b/src/errors.js @@ -144,12 +144,23 @@ function init() { return class NodeError extends Super { constructor(...args) { const template = templateMap.get(code) + super(template(...args)) - if (code === "MODULE_NOT_FOUND") { - this.code = code - this.name = super.name - } + const name = toString(get(this, "name")) + + // Add the error code to the name to include it in the stack trace. + Reflect.defineProperty(this, "name", { + configurable: true, + value: name + " [" + code + "]", + writable: true + }) + + // Access the stack to generate the error message including the error + // code from the name. + get(this, "stack") + // Reset the name to the actual name. + Reflect.deleteProperty(this, "name") } get code() { @@ -159,14 +170,6 @@ function init() { set code(value) { setProperty(this, "code", value) } - - get name() { - return super.name + " [" + code + "]" - } - - set name(value) { - setProperty(this, "name", value) - } } } diff --git a/test/misc-tests.js b/test/misc-tests.js index 5a8a6e343..48afd9eeb 100644 --- a/test/misc-tests.js +++ b/test/misc-tests.js @@ -49,30 +49,9 @@ const defNs = createNamespace({ function checkError(error, code) { const { message } = error - checkErrorProps(error, code, message) - checkErrorCustomProps(error, code, message) - checkErrorProps(error, code, message) -} - -function checkErrorCustomProps(error, code, message) { - error.code = "ERR_CUSTOM" - - assert.strictEqual(error.code, "ERR_CUSTOM") - assert.strictEqual(error.toString(), "Error [" + code + "]: " + message) - - error.name = "Custom" - - assert.strictEqual(error.name, "Custom") - assert.strictEqual(error.toString(), "Custom: " + message) - - Reflect.deleteProperty(error, "code") - Reflect.deleteProperty(error, "name") -} - -function checkErrorProps(error, code, message) { assert.strictEqual(error.code, code) - assert.strictEqual(error.name, "Error [" + code + "]") - assert.strictEqual(error.toString(), "Error [" + code + "]: " + message) + assert.strictEqual(error.message, message) + assert.strictEqual(error.name, "Error") assert.deepStrictEqual(Object.keys(error), []) assert.deepStrictEqual(Object.getOwnPropertySymbols(error), []) }