From 12023dff4b452b3d64bb2146c6cc501cd956ea62 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 28 Nov 2021 12:22:29 -0800 Subject: [PATCH] errors: add support for cause in aborterror Signed-off-by: James M Snell PR-URL: https://github.com/nodejs/node/pull/41008 Reviewed-By: Ruben Bridgewater Reviewed-By: Robert Nagy Reviewed-By: Benjamin Gruenbaum --- lib/internal/errors.js | 7 ++++-- test/parallel/test-errors-aborterror.js | 31 +++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) create mode 100644 test/parallel/test-errors-aborterror.js diff --git a/lib/internal/errors.js b/lib/internal/errors.js index 4dadb268cea683..309f6bb3105341 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -821,8 +821,11 @@ function hideInternalStackFrames(error) { // to make usage of the error in userland and readable-stream easier. // It is a regular error with `.code` and `.name`. class AbortError extends Error { - constructor() { - super('The operation was aborted'); + constructor(message = 'The operation was aborted', options = undefined) { + if (options !== undefined && typeof options !== 'object') { + throw new codes.ERR_INVALID_ARG_TYPE('options', 'Object', options); + } + super(message, options); this.code = 'ABORT_ERR'; this.name = 'AbortError'; } diff --git a/test/parallel/test-errors-aborterror.js b/test/parallel/test-errors-aborterror.js new file mode 100644 index 00000000000000..15da9f06f94b4d --- /dev/null +++ b/test/parallel/test-errors-aborterror.js @@ -0,0 +1,31 @@ +// Flags: --expose-internals +'use strict'; + +require('../common'); +const { + strictEqual, + throws, +} = require('assert'); +const { AbortError } = require('internal/errors'); + +{ + const err = new AbortError(); + strictEqual(err.message, 'The operation was aborted'); + strictEqual(err.cause, undefined); +} + +{ + const cause = new Error('boom'); + const err = new AbortError('bang', { cause }); + strictEqual(err.message, 'bang'); + strictEqual(err.cause, cause); +} + +{ + throws(() => new AbortError('', false), { + code: 'ERR_INVALID_ARG_TYPE' + }); + throws(() => new AbortError('', ''), { + code: 'ERR_INVALID_ARG_TYPE' + }); +}