Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 22 additions & 14 deletions src/core/services/HttpClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,27 @@ export class HttpClient {
return url;
}

/**
* Safely parses a JSON response, handling cases where the body might be empty or invalid JSON.
* This prevents "body already consumed" errors by reading text first, then parsing.
*/
private async safeJson(response: Response): Promise<any> {
if (response.status === 204) {
// No Content
return {};
}
let text = 'Failed to parse response body';
try {
text = await response.text();
return JSON.parse(text);
} catch {
return {
error: 'invalid_json',
error_description: text,
};
}
}

private async request<T>(
url: string,
method: 'GET' | 'POST' | 'PATCH',
Expand All @@ -91,20 +112,7 @@ export class HttpClient {
this.timeout
);

let json: any;
if (response.status === 204) {
// No Content
json = {};
} else {
try {
json = await response.json();
} catch {
json = {
error: 'invalid_json',
error_description: await response.text(),
};
}
}
const json = await this.safeJson(response);

return { json: json as T, response };
} catch (e) {
Expand Down