From 9ca9e815f468a3cddd768472130543c9b7187d17 Mon Sep 17 00:00:00 2001 From: Joyee Cheung Date: Tue, 28 Aug 2018 03:57:23 +0800 Subject: [PATCH] errors: add useOriginalName to internal/errors This allows us to tell the type of the errors without using instanceof, which is necessary in WPT harness. PR-URL: https://github.com/nodejs/node/pull/22556 Reviewed-By: John-David Dalton Reviewed-By: Gus Caplan Reviewed-By: Ruben Bridgewater Reviewed-By: Refael Ackermann --- lib/internal/errors.js | 12 ++++++- .../test-internal-error-original-names.js | 35 +++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 test/parallel/test-internal-error-original-names.js diff --git a/lib/internal/errors.js b/lib/internal/errors.js index 9ecad0aee920eb..8f438d343a10d6 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -151,6 +151,8 @@ function makeSystemErrorWithCode(key) { }; } +let useOriginalName = false; + function makeNodeErrorWithCode(Base, key) { return class NodeError extends Base { constructor(...args) { @@ -158,6 +160,9 @@ function makeNodeErrorWithCode(Base, key) { } get name() { + if (useOriginalName) { + return super.name; + } return `${super.name} [${key}]`; } @@ -439,7 +444,12 @@ module.exports = { getMessage, SystemError, codes, - E // This is exported only to facilitate testing. + // This is exported only to facilitate testing. + E, + // This allows us to tell the type of the errors without using + // instanceof, which is necessary in WPT harness. + get useOriginalName() { return useOriginalName; }, + set useOriginalName(value) { useOriginalName = value; } }; // To declare an error message, use the E(sym, val, def) function above. The sym diff --git a/test/parallel/test-internal-error-original-names.js b/test/parallel/test-internal-error-original-names.js new file mode 100644 index 00000000000000..195e39b199cd4c --- /dev/null +++ b/test/parallel/test-internal-error-original-names.js @@ -0,0 +1,35 @@ +// Flags: --expose-internals + +'use strict'; + +// This tests `internal/errors.useOriginalName` +// This testing feature is needed to allows us to assert the types of +// errors without using instanceof, which is necessary in WPT harness. +// Refs: https://github.com/nodejs/node/pull/22556 + +require('../common'); +const assert = require('assert'); +const errors = require('internal/errors'); + + +errors.E('TEST_ERROR_1', 'Error for testing purposes: %s', + Error); +{ + const err = new errors.codes.TEST_ERROR_1('test'); + assert(err instanceof Error); + assert.strictEqual(err.name, 'Error [TEST_ERROR_1]'); +} + +{ + errors.useOriginalName = true; + const err = new errors.codes.TEST_ERROR_1('test'); + assert(err instanceof Error); + assert.strictEqual(err.name, 'Error'); +} + +{ + errors.useOriginalName = false; + const err = new errors.codes.TEST_ERROR_1('test'); + assert(err instanceof Error); + assert.strictEqual(err.name, 'Error [TEST_ERROR_1]'); +}