Skip to content

Commit a36702e

Browse files
kanongilMarsup
authored andcommitted
Fix cloning Util.inherit() subclassed errors. Closes #400
1 parent fdb908e commit a36702e

File tree

2 files changed

+34
-3
lines changed

2 files changed

+34
-3
lines changed

lib/clone.js

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -166,10 +166,12 @@ internals.base = function (obj, baseProto, options) {
166166

167167
return newObj;
168168
}
169-
else if (baseProto === Types.error) {
170-
const err = structuredClone(obj); // Needed to copy internal stack state
169+
else if (baseProto === Types.error &&
170+
(proto === baseProto || Error.isPrototypeOf(proto.constructor))) { // Don't match Util.inherit() subclassed errors
171+
172+
const err = structuredClone(obj); // Needed to copy internal stack state
171173
if (Object.getPrototypeOf(err) !== proto) {
172-
Object.setPrototypeOf(err, proto); // Fix prototype
174+
Object.setPrototypeOf(err, proto); // Fix prototype
173175
}
174176

175177
return err;

test/clone.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -731,6 +731,35 @@ describe('clone()', () => {
731731
expect(b.stack).to.equal(a.stack);
732732
});
733733

734+
it('clones Error with function property', () => {
735+
736+
const a = new Error('hello');
737+
a.fun = new Function();
738+
739+
const b = Hoek.clone(a);
740+
741+
expect(b).to.equal(a);
742+
expect(b.stack).to.equal(a.stack);
743+
});
744+
745+
it('clones legacy extended Error with function property', () => {
746+
747+
const CustomError = function () {
748+
749+
Error.call(this);
750+
};
751+
752+
Object.setPrototypeOf(CustomError.prototype, Error.prototype);
753+
754+
const a = new CustomError('hello');
755+
a.fun = new Function();
756+
757+
const b = Hoek.clone(a);
758+
759+
expect(b).to.equal(a);
760+
expect(b.stack).to.equal(a.stack);
761+
});
762+
734763
it('cloned Error handles late stack update', () => {
735764

736765
const a = new Error('bad');

0 commit comments

Comments
 (0)