From c87186757e453f6bf721be4012794c756a4d8d7e 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 | 21 +++++++++++---- test/parallel/test-domexception-cause.js | 33 ++++++++++++++++++++++++ 2 files changed, 49 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..01893dc3d81e79 100644 --- a/lib/internal/per_context/domexception.js +++ b/lib/internal/per_context/domexception.js @@ -49,12 +49,23 @@ 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, cause } = options; + internalsMap.set(this, { + message: `${message}`, + name: `${name}` + }); + + ObjectDefineProperty(this, 'cause', { __proto__: null, value: cause }); + } 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..122636fe33e6b5 --- /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); +}