@@ -197,6 +197,19 @@ async function createUploadRequest(
197197 return await getResponse ( req )
198198}
199199
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+
200213function getHttpModule ( baseUrl : string ) : typeof http | typeof https {
201214 const { protocol } = new URL ( baseUrl )
202215 return protocol === 'https:' ? https : http
@@ -358,29 +371,20 @@ export class SocketSdk {
358371 cause : error
359372 } )
360373 }
361-
362374 // 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.
373377 let body
374378 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
379384 }
380385 } catch {
381386 body = bodyStr
382387 }
383-
384388 return {
385389 success : false as const ,
386390 status : statusCode ! ,
0 commit comments