Skip to content

Commit 0179f79

Browse files
committed
Implement a safeStringify method that is the fallback if formatJson fails in the browser.
1 parent a4897a6 commit 0179f79

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

packages/firestore/src/platform/browser/format_json.ts

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,5 +17,29 @@
1717

1818
/** Formats an object as a JSON string, suitable for logging. */
1919
export function formatJSON(value: unknown): string {
20-
return JSON.stringify(value);
20+
try {
21+
return JSON.stringify(value);
22+
} catch (e: unknown) {
23+
return safeStringify(value);
24+
}
25+
}
26+
27+
/**
28+
* Custom JSON stringification utilizing a replacer to work around common
29+
* JSON.stringify(...) error cases: circular reference or bigint.
30+
* @param value - object to stringify
31+
*/
32+
function safeStringify(value: unknown): string {
33+
const cache = new Set();
34+
return JSON.stringify(value, (key, value) => {
35+
if (typeof value === 'object' && value !== null) {
36+
if (cache.has(value)) {
37+
return '[Circular]';
38+
}
39+
cache.add(value);
40+
} else if (typeof value === 'bigint') {
41+
return value.toString();
42+
}
43+
return value;
44+
});
2145
}

packages/firestore/src/platform/browser/webchannel_connection.ts

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -335,9 +335,7 @@ export class WebChannelConnection extends RestConnection {
335335
logWarn(
336336
LOG_TAG,
337337
`RPC '${rpcName}' stream ${streamId} transport errored. Name:`,
338-
err.name,
339-
'Message:',
340-
err.message
338+
err
341339
);
342340
streamBridge.callOnClose(
343341
new FirestoreError(

0 commit comments

Comments
 (0)