fix: handle edge case where JSON.stringify returns undefined

Add fallback to String() when JSON.stringify returns undefined,
which can happen with objects that have toJSON() returning undefined.
This commit is contained in:
Tu Shaokun 2026-01-01 10:10:24 +08:00
parent 7fdebe8fe6
commit 4f664d00ac
2 changed files with 12 additions and 1 deletions

View file

@ -125,6 +125,15 @@ describe('errors', () => {
const obj = { message: 123 };
expect(getErrorMessage(obj)).toBe('{"message":123}');
});
it('should fallback to String() when toJSON returns undefined', () => {
const obj = {
toJSON() {
return undefined;
},
};
expect(getErrorMessage(obj)).toBe('[object Object]');
});
});
describe('handleError', () => {

View file

@ -31,7 +31,9 @@ export function getErrorMessage(error: unknown): string {
// Handle plain objects by stringifying them
if (error !== null && typeof error === 'object') {
try {
return JSON.stringify(error);
const stringified = JSON.stringify(error);
// JSON.stringify can return undefined for objects with toJSON() returning undefined
return stringified ?? String(error);
} catch {
// If JSON.stringify fails (circular reference, etc.), fall back to String
return String(error);