Skip to content

Commit

Permalink
Custom error cloning to fix node v21 issue
Browse files Browse the repository at this point in the history
  • Loading branch information
kanongil authored and Marsup committed Oct 23, 2024
1 parent f98bfdf commit a554a8b
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
14 changes: 14 additions & 0 deletions lib/clone.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,12 @@ module.exports = internals.clone = function (obj, options = {}, _seen = null) {
continue;
}

if (baseProto === Types.error &&
(key === 'message' || key === 'stack')) {

continue; // Already a part of the base object
}

const descriptor = Object.getOwnPropertyDescriptor(obj, key);
if (descriptor) {
if (descriptor.get ||
Expand Down Expand Up @@ -162,6 +168,14 @@ internals.base = function (obj, baseProto, options) {

return newObj;
}
else if (baseProto === Types.error) {
const err = structuredClone(obj); // Needed to copy internal stack state
if (proto !== baseProto) {
Object.setPrototypeOf(err, proto); // Fix prototype
}

return err;
}

if (internals.needsProtoHack.has(baseProto)) {
const newObj = new proto.constructor();
Expand Down
28 changes: 28 additions & 0 deletions test/clone.js
Original file line number Diff line number Diff line change
Expand Up @@ -680,6 +680,34 @@ describe('clone()', () => {
expect(b.get(nestedObj)).to.equal(a.get(nestedObj));
});

it('clones Error', () => {

class CustomError extends Error {
name = 'CustomError';
}

const a = new CustomError('bad');
a.test = Symbol('test');

const b = Hoek.clone(a);

expect(b).to.equal(a);
expect(b).to.not.shallow.equal(a);
expect(b).to.be.instanceOf(CustomError);
expect(b.stack).to.equal(a.stack); // Explicitly validate the .stack getters
});

it('cloned Error handles late stack update', () => {

const a = new Error('bad');
const b = Hoek.clone(a);

a.stack = 'late update';

expect(b).to.equal(a);
expect(b.stack).to.not.equal(a.stack);
});

it('ignores symbols', () => {

const sym = Symbol();
Expand Down

0 comments on commit a554a8b

Please sign in to comment.