From a81a7946c735511c769d90e6fea21c382e03f6d6 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 | 23 +++++++++++++---- test/parallel/test-domexception-cause.js | 33 ++++++++++++++++++++++++ 2 files changed, 51 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..39f1ee6e715df9 100644 --- a/lib/internal/per_context/domexception.js +++ b/lib/internal/per_context/domexception.js @@ -49,12 +49,25 @@ 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: 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..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); +}