@@ -197,6 +197,19 @@ async function createUploadRequest(
197
197
return await getResponse ( req )
198
198
}
199
199
200
+ async function getErrorResponseBody (
201
+ response : IncomingMessage
202
+ ) : Promise < string > {
203
+ const chunks : Buffer [ ] = [ ]
204
+ response . on ( 'data' , ( chunk : Buffer ) => chunks . push ( chunk ) )
205
+ try {
206
+ await events . once ( response , 'end' )
207
+ return Buffer . concat ( chunks ) . toString ( 'utf8' )
208
+ } catch {
209
+ return '(there was an error reading the body content)'
210
+ }
211
+ }
212
+
200
213
function getHttpModule ( baseUrl : string ) : typeof http | typeof https {
201
214
const { protocol } = new URL ( baseUrl )
202
215
return protocol === 'https:' ? https : http
@@ -358,29 +371,20 @@ export class SocketSdk {
358
371
cause : error
359
372
} )
360
373
}
361
-
362
374
// The error payload may give a meaningful hint as to what went wrong.
363
-
364
- const bodyStr = await new Promise ( ( resolve ) => {
365
- const chunks : Buffer [ ] = [ ] ;
366
- error . response . on ( 'data' , ( chunk :Buffer ) => chunks . push ( chunk ) ) ;
367
- error . response . on ( 'end' , ( ) => resolve ( Buffer . concat ( chunks ) . toString ( 'utf8' ) ) ) ;
368
- error . response . on ( 'error' , ( ) => resolve ( '(there was an error reading the body content)' ) ) ;
369
- } ) ;
370
-
371
- // Try to parse the body as JSON, fallback to treating it as plaintext
372
-
375
+ const bodyStr = await getErrorResponseBody ( error . response )
376
+ // Try to parse the body as JSON, fallback to treating as plain text.
373
377
let body
374
378
try {
375
- body = JSON . parse ( String ( bodyStr || '' ) ) as any
376
- // A 400 should return an actionable message
377
- if ( body ?. error ?. message ) {
378
- body = body . error . message
379
+ const parsed = JSON . parse ( bodyStr )
380
+ // A 400 should return an actionable message.
381
+ // TODO: Do we care about the body.error.details object?
382
+ if ( typeof parsed ?. error ?. message === 'string' ) {
383
+ body = parsed . error . message
379
384
}
380
385
} catch {
381
386
body = bodyStr
382
387
}
383
-
384
388
return {
385
389
success : false as const ,
386
390
status : statusCode ! ,
0 commit comments