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); +}