From 3bf230e832c38310c84482f59ef5e37b4160eb3e Mon Sep 17 00:00:00 2001 From: Subhankar Maiti Date: Mon, 1 Dec 2025 17:51:36 +0530 Subject: [PATCH 1/2] fix: Handle 401 response parsing correctly in userInfo endpoint --- src/core/services/HttpClient.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/core/services/HttpClient.ts b/src/core/services/HttpClient.ts index dc894023..79fbf29b 100644 --- a/src/core/services/HttpClient.ts +++ b/src/core/services/HttpClient.ts @@ -96,12 +96,14 @@ export class HttpClient { // No Content json = {}; } else { + // Read text first to avoid body-already-consumed errors when JSON parsing fails + const text = await response.text(); try { - json = await response.json(); + json = JSON.parse(text); } catch { json = { error: 'invalid_json', - error_description: await response.text(), + error_description: text, }; } } From 542fc3a8c5c764532b74e7d60c3f636233fa6cfc Mon Sep 17 00:00:00 2001 From: Subhankar Maiti Date: Mon, 1 Dec 2025 18:42:01 +0530 Subject: [PATCH 2/2] fix: refactor safeJson method to improve JSON response parsing and handle empty responses --- src/core/services/HttpClient.ts | 38 +++++++++++++++++++-------------- 1 file changed, 22 insertions(+), 16 deletions(-) diff --git a/src/core/services/HttpClient.ts b/src/core/services/HttpClient.ts index 79fbf29b..ff86f988 100644 --- a/src/core/services/HttpClient.ts +++ b/src/core/services/HttpClient.ts @@ -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 { + 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( url: string, method: 'GET' | 'POST' | 'PATCH', @@ -91,22 +112,7 @@ export class HttpClient { this.timeout ); - let json: any; - if (response.status === 204) { - // No Content - json = {}; - } else { - // Read text first to avoid body-already-consumed errors when JSON parsing fails - const text = await response.text(); - try { - json = JSON.parse(text); - } catch { - json = { - error: 'invalid_json', - error_description: text, - }; - } - } + const json = await this.safeJson(response); return { json: json as T, response }; } catch (e) {