File tree Expand file tree Collapse file tree 1 file changed +22
-14
lines changed
Expand file tree Collapse file tree 1 file changed +22
-14
lines changed Original file line number Diff line number Diff 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,20 +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- try {
100- json = await response . json ( ) ;
101- } catch {
102- json = {
103- error : 'invalid_json' ,
104- error_description : await response . text ( ) ,
105- } ;
106- }
107- }
115+ const json = await this . safeJson ( response ) ;
108116
109117 return { json : json as T , response } ;
110118 } catch ( e ) {
You can’t perform that action at this time.
0 commit comments