Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix cloning Util.inherit() subclassed errors. Backports #401 #402

Merged
merged 1 commit into from
Nov 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions lib/clone.js
Original file line number Diff line number Diff line change
Expand Up @@ -173,10 +173,12 @@ internals.base = function (obj, baseProto, options) {
}
// Can only be covered in node 21+
/* $lab:coverage:off$ */
else if (baseProto === Types.error && internals.structuredCloneExists) {
const err = structuredClone(obj); // Needed to copy internal stack state
else if (baseProto === Types.error && internals.structuredCloneExists &&
(proto === baseProto || Error.isPrototypeOf(proto.constructor))) { // Don't match Util.inherit() subclassed errors

const err = structuredClone(obj); // Needed to copy internal stack state
if (Object.getPrototypeOf(err) !== proto) {
Object.setPrototypeOf(err, proto); // Fix prototype
Object.setPrototypeOf(err, proto); // Fix prototype
}

return err;
Expand Down
29 changes: 29 additions & 0 deletions test/clone.js
Original file line number Diff line number Diff line change
Expand Up @@ -731,6 +731,35 @@ describe('clone()', () => {
expect(b.stack).to.equal(a.stack);
});

it('clones Error with function property', () => {

const a = new Error('hello');
a.fun = new Function();

const b = Hoek.clone(a);

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

it('clones legacy extended Error with function property', () => {

const CustomError = function () {

Error.call(this);
};

Object.setPrototypeOf(CustomError.prototype, Error.prototype);

const a = new CustomError('hello');
a.fun = new Function();

const b = Hoek.clone(a);

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

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

const a = new Error('bad');
Expand Down