Skip to content

Commit 667e726

Browse files
committed
Refactor error handling in request and requestHref functions to improve JSON parsing and status code retrieval
1 parent 27d654e commit 667e726

File tree

1 file changed

+25
-7
lines changed

1 file changed

+25
-7
lines changed

src/shared/request.ts

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -67,9 +67,18 @@ export async function request(requestOptions: RequestOptions) {
6767
return await response.json();
6868
}
6969

70-
const errorData = await response.json() as BlizzardAPIErrorResponse;
71-
const statusCode = errorData.code || response.status;
72-
const errorMessage = JSON.stringify(errorData) || "Problem fetching data from API";
70+
const text = await response.text();
71+
let errorData: BlizzardAPIErrorResponse | null = null;
72+
try {
73+
errorData = text ? (JSON.parse(text) as BlizzardAPIErrorResponse) : null;
74+
} catch {
75+
// Empty or non-JSON body (e.g. 404 with no body)
76+
}
77+
const statusCode = errorData?.code ?? response.status;
78+
const errorMessage = errorData
79+
? JSON.stringify(errorData)
80+
: response.statusText || "Problem fetching data from API";
81+
7382
throw new APIError(errorMessage, statusCode, response.statusText);
7483
}
7584

@@ -119,7 +128,7 @@ export async function requestHref(href: string, qs?: Record<string, string | num
119128
}
120129

121130
const fullUrl = href + (queryString ? (href.includes("?") ? "&" : "?") + queryString : "");
122-
console.log(fullUrl);
131+
123132
const response = await fetch(fullUrl, {
124133
method: "GET",
125134
headers: headers,
@@ -129,8 +138,17 @@ export async function requestHref(href: string, qs?: Record<string, string | num
129138
return await response.json();
130139
}
131140

132-
const errorData = await response.json() as BlizzardAPIErrorResponse;
133-
const statusCode = errorData.code || response.status;
134-
const errorMessage = JSON.stringify(errorData) || "Problem fetching data from API";
141+
const text = await response.text();
142+
let errorData: BlizzardAPIErrorResponse | null = null;
143+
try {
144+
errorData = text ? (JSON.parse(text) as BlizzardAPIErrorResponse) : null;
145+
} catch {
146+
// Empty or non-JSON body
147+
}
148+
const statusCode = errorData?.code ?? response.status;
149+
const errorMessage = errorData
150+
? JSON.stringify(errorData)
151+
: response.statusText || "Problem fetching data from API";
152+
135153
throw new APIError(errorMessage, statusCode, response.statusText);
136154
}

0 commit comments

Comments
 (0)