Skip to content

Commit

Permalink
errors: add useOriginalName to internal/errors
Browse files Browse the repository at this point in the history
This allows us to tell the type of the errors without using
instanceof, which is necessary in WPT harness.

PR-URL: #22556
Reviewed-By: John-David Dalton <[email protected]>
Reviewed-By: Gus Caplan <[email protected]>
Reviewed-By: Ruben Bridgewater <[email protected]>
Reviewed-By: Refael Ackermann <[email protected]>
  • Loading branch information
joyeecheung authored and targos committed Sep 19, 2018
1 parent 325b82a commit 9ca9e81
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
12 changes: 11 additions & 1 deletion lib/internal/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -151,13 +151,18 @@ function makeSystemErrorWithCode(key) {
};
}

let useOriginalName = false;

function makeNodeErrorWithCode(Base, key) {
return class NodeError extends Base {
constructor(...args) {
super(getMessage(key, args));
}

get name() {
if (useOriginalName) {
return super.name;
}
return `${super.name} [${key}]`;
}

Expand Down Expand Up @@ -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
Expand Down
35 changes: 35 additions & 0 deletions test/parallel/test-internal-error-original-names.js
Original file line number Diff line number Diff line change
@@ -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]');
}

0 comments on commit 9ca9e81

Please sign in to comment.