Skip to content

Commit b560485

Browse files
committed
refactor: better req json parse error handling
1 parent 06b82d7 commit b560485

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

.changeset/stupid-avocados-rush.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@squarecloud/api": patch
3+
---
4+
5+
Better request JSON parse error debugging.

src/services/api.ts

+21-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import type { APIVersion } from "@squarecloud/api-types/v2";
22

3+
import { existsSync } from "node:fs";
4+
import { mkdir, writeFile } from "node:fs/promises";
35
import { SquareCloudAPIError } from "@/structures";
46
import type {
57
APIEndpoint,
@@ -25,7 +27,9 @@ export class APIService {
2527
const response = await fetch(url, init).catch((err) => {
2628
throw new SquareCloudAPIError(err.code, err.message);
2729
});
28-
const data = await response.json();
30+
const data = await response
31+
.json()
32+
.catch(() => this.handleParseError(response));
2933

3034
if (!data || data.status === "error" || !response.ok) {
3135
throw new SquareCloudAPIError(data?.code || "COMMON_ERROR");
@@ -65,4 +69,20 @@ export class APIService {
6569

6670
return { url, init };
6771
}
72+
73+
private async handleParseError(response: Response) {
74+
const text = await response.text();
75+
const dir = ".squarecloud/logs/";
76+
const path = `${dir}${this.userId}-${Date.now()}.log`;
77+
78+
if (!existsSync(dir)) {
79+
await mkdir(dir);
80+
}
81+
await writeFile(path, text);
82+
83+
throw new SquareCloudAPIError(
84+
"CANNOT_PARSE_JSON",
85+
`Saved request text content to ${path}`,
86+
);
87+
}
6888
}

0 commit comments

Comments
 (0)