From 261bbb245edf504a510a9d79bf14f0117ac0929e Mon Sep 17 00:00:00 2001 From: flakey5 <73616808+flakey5@users.noreply.github.com> Date: Sat, 17 Sep 2022 12:49:30 -0700 Subject: [PATCH] lib: add cause to DOMException --- lib/internal/per_context/domexception.js | 29 +++++++++++++++++---- test/parallel/test-domexception-cause.js | 33 ++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 5 deletions(-) create mode 100644 test/parallel/test-domexception-cause.js diff --git a/lib/internal/per_context/domexception.js b/lib/internal/per_context/domexception.js index 917e2c00bccda9..a0814894524a23 100644 --- a/lib/internal/per_context/domexception.js +++ b/lib/internal/per_context/domexception.js @@ -49,12 +49,31 @@ const disusedNamesSet = new SafeSet() .add('ValidationError'); class DOMException { - constructor(message = '', name = 'Error') { + constructor(message = '', options = 'Error') { ErrorCaptureStackTrace(this); - internalsMap.set(this, { - message: `${message}`, - name: `${name}` - }); + + if (options && typeof options === 'object') { + const { name } = options; + internalsMap.set(this, { + message: `${message}`, + name: `${name}` + }); + + if ('cause' in options) { + ObjectDefineProperty(this, 'cause', { + __proto__: null, + value: options.cause, + configurable: true, + writable: true, + enumerable: false, + }); + } + } else { + internalsMap.set(this, { + message: `${message}`, + name: `${options}` + }); + } } get name() { diff --git a/test/parallel/test-domexception-cause.js b/test/parallel/test-domexception-cause.js new file mode 100644 index 00000000000000..179ef6d212ae13 --- /dev/null +++ b/test/parallel/test-domexception-cause.js @@ -0,0 +1,33 @@ +'use strict'; + +require('../common'); +const { strictEqual, deepStrictEqual } = require('assert'); + +{ + const domException = new DOMException('no cause', 'abc'); + strictEqual(domException.name, 'abc'); + strictEqual('cause' in domException, false); + strictEqual(domException.cause, undefined); +} + +{ + const domException = new DOMException('with undefined cause', { name: 'abc', cause: undefined }); + strictEqual(domException.name, 'abc'); + strictEqual('cause' in domException, true); + strictEqual(domException.cause, undefined); +} + +{ + const domException = new DOMException('with string cause', { name: 'abc', cause: 'foo' }); + strictEqual(domException.name, 'abc'); + strictEqual('cause' in domException, true); + strictEqual(domException.cause, 'foo'); +} + +{ + const object = { reason: 'foo' }; + const domException = new DOMException('with object cause', { name: 'abc', cause: object }); + strictEqual(domException.name, 'abc'); + strictEqual('cause' in domException, true); + deepStrictEqual(domException.cause, object); +}