From 7c7f86c2e712697daa1c55cb1c2628699f0fda30 Mon Sep 17 00:00:00 2001 From: Gil Pedersen Date: Thu, 7 Dec 2023 11:36:27 +0100 Subject: [PATCH] Assign .cause if not handled by super() call --- lib/index.js | 4 ++++ test/index.js | 21 +++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/lib/index.js b/lib/index.js index 22a4925..314f7c2 100755 --- a/lib/index.js +++ b/lib/index.js @@ -85,6 +85,10 @@ exports.Boom = class Boom extends Error { super(message ?? internals.codes.get(statusCode) ?? 'Unknown', { cause }); Error.captureStackTrace(this, ctor); // Filter the stack to our external API + if (cause !== undefined) { + this.cause ??= cause; // Explicitly assign cause to work with old runtimes + } + internals.apply(this, data, statusCode, headers); } diff --git a/test/index.js b/test/index.js index e122020..dd63d65 100755 --- a/test/index.js +++ b/test/index.js @@ -122,6 +122,27 @@ describe('Boom', () => { expect(err.output.payload.error).to.equal('Unknown'); }); + it('assigns a .cause property if Error does not support it', (flags) => { + + const proto = Object.getPrototypeOf(Boom.Boom); + Object.setPrototypeOf(Boom.Boom, class extends Error { + + constructor(message, _options) { + + super(message); + } + }); + + flags.onCleanup = () => { + + Object.setPrototypeOf(Boom.Boom, proto); + }; + + const err = new Boom.Boom('fail', { cause: 0 }); + expect(err.cause).to.exist(); + expect(err.cause).to.equal(0); + }); + describe('instanceof', () => { it('identifies a boom object', () => {