Skip to content

Commit 52a0522

Browse files
committed
Fixed call stack overflow in makeError stringify for recursive structures (#4977, #4978).
1 parent fe98f98 commit 52a0522

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

src.ts/utils/errors.ts

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,17 @@ import type { FetchRequest, FetchResponse } from "./fetch.js";
2525
export type ErrorInfo<T> = Omit<T, "code" | "name" | "message" | "shortMessage"> & { shortMessage?: string };
2626

2727

28-
function stringify(value: any): any {
28+
function stringify(value: any, seen?: Set<any>): any {
2929
if (value == null) { return "null"; }
3030

31+
if (seen == null) { seen = new Set(); }
32+
if (typeof(value) === "object") {
33+
if (seen.has(value)) { return "[Circular]"; }
34+
seen.add(value);
35+
}
36+
3137
if (Array.isArray(value)) {
32-
return "[ " + (value.map(stringify)).join(", ") + " ]";
38+
return "[ " + (value.map((v) => stringify(v, seen))).join(", ") + " ]";
3339
}
3440

3541
if (value instanceof Uint8Array) {
@@ -43,22 +49,20 @@ function stringify(value: any): any {
4349
}
4450

4551
if (typeof(value) === "object" && typeof(value.toJSON) === "function") {
46-
return stringify(value.toJSON());
52+
return stringify(value.toJSON(), seen);
4753
}
4854

4955
switch (typeof(value)) {
50-
case "boolean": case "symbol":
56+
case "boolean": case "number": case "symbol":
5157
return value.toString();
5258
case "bigint":
5359
return BigInt(value).toString();
54-
case "number":
55-
return (value).toString();
5660
case "string":
5761
return JSON.stringify(value);
5862
case "object": {
5963
const keys = Object.keys(value);
6064
keys.sort();
61-
return "{ " + keys.map((k) => `${ stringify(k) }: ${ stringify(value[k]) }`).join(", ") + " }";
65+
return "{ " + keys.map((k) => `${ stringify(k, seen) }: ${ stringify(value[k], seen) }`).join(", ") + " }";
6266
}
6367
}
6468

0 commit comments

Comments
 (0)