Skip to content

Commit 542fc3a

Browse files
fix: refactor safeJson method to improve JSON response parsing and handle empty responses
1 parent 3bf230e commit 542fc3a

1 file changed

Lines changed: 22 additions & 16 deletions

File tree

src/core/services/HttpClient.ts

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,27 @@ export class HttpClient {
7070
return url;
7171
}
7272

73+
/**
74+
* Safely parses a JSON response, handling cases where the body might be empty or invalid JSON.
75+
* This prevents "body already consumed" errors by reading text first, then parsing.
76+
*/
77+
private async safeJson(response: Response): Promise<any> {
78+
if (response.status === 204) {
79+
// No Content
80+
return {};
81+
}
82+
let text = 'Failed to parse response body';
83+
try {
84+
text = await response.text();
85+
return JSON.parse(text);
86+
} catch {
87+
return {
88+
error: 'invalid_json',
89+
error_description: text,
90+
};
91+
}
92+
}
93+
7394
private async request<T>(
7495
url: string,
7596
method: 'GET' | 'POST' | 'PATCH',
@@ -91,22 +112,7 @@ export class HttpClient {
91112
this.timeout
92113
);
93114

94-
let json: any;
95-
if (response.status === 204) {
96-
// No Content
97-
json = {};
98-
} else {
99-
// Read text first to avoid body-already-consumed errors when JSON parsing fails
100-
const text = await response.text();
101-
try {
102-
json = JSON.parse(text);
103-
} catch {
104-
json = {
105-
error: 'invalid_json',
106-
error_description: text,
107-
};
108-
}
109-
}
115+
const json = await this.safeJson(response);
110116

111117
return { json: json as T, response };
112118
} catch (e) {

0 commit comments

Comments
 (0)