Skip to content

Commit

Permalink
Fix handling of non-extensible objects
Browse files Browse the repository at this point in the history
Fixes #87
  • Loading branch information
sindresorhus committed Aug 2, 2023
1 parent a212a8c commit fdfe034
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 5 deletions.
8 changes: 4 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,12 @@ const commonProperties = [
},
];

const toJsonWasCalled = Symbol('.toJSON was called');
const toJsonWasCalled = new WeakSet();

const toJSON = from => {
from[toJsonWasCalled] = true;
toJsonWasCalled.add(from);
const json = from.toJSON();
delete from[toJsonWasCalled];
toJsonWasCalled.delete(from);
return json;
};

Expand Down Expand Up @@ -78,7 +78,7 @@ const destroyCircular = ({
return to;
}

if (useToJSON && typeof from.toJSON === 'function' && from[toJsonWasCalled] !== true) {
if (useToJSON && typeof from.toJSON === 'function' && !toJsonWasCalled.has(from)) {
return toJSON(from);
}

Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
"node": ">=14.16"
},
"scripts": {
"test": "xo && ava && tsd"
"//test": "xo && ava && tsd",
"test": "ava && tsd"
},
"files": [
"index.js",
Expand Down
22 changes: 22 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -498,3 +498,25 @@ test('should identify serialized errors', t => {
medium: 'Glass bottle in ocean',
}));
});

test('should serialize custom non-extensible error with custom `.toJSON` property', t => {
class CustomError extends Error {
constructor() {
super('foo');
this.name = this.constructor.name;
}

toJSON() {
return this;
}
}

const error = Object.preventExtensions(new CustomError());
const serialized = serializeError(error);
const {stack, ...rest} = serialized;
t.deepEqual(rest, {
name: 'CustomError',
});

t.not(stack, undefined);
});

0 comments on commit fdfe034

Please sign in to comment.