Skip to content

Commit

Permalink
Fix compatibility with DOMException
Browse files Browse the repository at this point in the history
  • Loading branch information
sindresorhus committed Aug 25, 2023
1 parent 786f5eb commit 26fc52b
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
9 changes: 7 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,11 @@ const destroyCircular = ({
}

if (!value || typeof value !== 'object') {
to[key] = value;
// Gracefully handle non-configurable errors like `DOMException`.
try {
to[key] = value;
} catch {}

continue;
}

Expand Down Expand Up @@ -159,7 +163,8 @@ export function serializeError(value, options = {}) {
// People sometimes throw things besides Error objects…
if (typeof value === 'function') {
// `JSON.stringify()` discards functions. We do too, unless a function is thrown directly.
return `[Function: ${value.name ?? 'anonymous'}]`;
// We intentionally use `||` because `.name` is an empty string for anonymous functions.
return `[Function: ${value.name || 'anonymous'}]`;
}

return value;
Expand Down
7 changes: 7 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -520,3 +520,10 @@ test('should serialize custom non-extensible error with custom `.toJSON` propert

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

if ('DOMException' in globalThis) {
test('should serialize DOMException', t => {
const serialized = serializeError(new DOMException('x'));
t.is(serialized.message, 'x');
});
}

0 comments on commit 26fc52b

Please sign in to comment.