@@ -1205,23 +1205,36 @@ export const Utils = {
12051205 logger . debug ( `settingResponse: START` ) ;
12061206 try {
12071207 const { promise, reject, resolve } = Utils . plugin . promiseWithResolver ( ) ;
1208- function callbackErrorWritingResponse ( error : Error | null | undefined ) {
1208+
1209+ const endResponse = ( ) => {
12091210 try {
1210- if ( error instanceof Error ) {
1211- logger . debug ( `settingResponse: ERROR - failed to write response ` , error as any ) ;
1212- res . statusCode = Constants . HTTP_STATUS_CODE . INTERNAL_SERVER_ERROR ;
1213- res . write ( JSON . stringify ( {
1211+ ! res . writableEnded && res . end ( ) ;
1212+ resolve ( null ) ;
1213+ } catch ( error ) {
1214+ reject ( error ) ;
1215+ }
1216+ } ;
1217+
1218+ function callbackErrorWritingResponse ( error : Error | null | undefined ) {
1219+ if ( error instanceof Error ) {
1220+ logger . debug ( `settingResponse: ERROR - failed to write response ` , error as any ) ;
1221+ if ( res . writableEnded ) {
1222+ resolve ( null ) ;
1223+ return ;
1224+ }
1225+ res . statusCode = Constants . HTTP_STATUS_CODE . INTERNAL_SERVER_ERROR ;
1226+ res . write (
1227+ JSON . stringify ( {
12141228 status : Constants . HTTP_STATUS_CODE . INTERNAL_SERVER_ERROR ,
12151229 error : Object . entries ( Constants . HTTP_STATUS_CODE ) . find ( el => el [ 1 ] === responseData . status ) ?. [ 0 ] ?? "Internal Server Error" ,
12161230 message : "Error writing response" ,
12171231 path : "" ,
12181232 timestamp : new Date ( ) . toISOString ( )
1219- } ) ) ;
1220- }
1221- ! res . writableEnded && res . end ( ) ;
1222- resolve ( null ) ;
1223- } catch ( error ) {
1224- reject ( error ) ;
1233+ } ) ,
1234+ endResponse
1235+ ) ;
1236+ } else {
1237+ endResponse ( ) ;
12251238 }
12261239 }
12271240 let responseData = data ;
@@ -1318,8 +1331,7 @@ export const Utils = {
13181331 if ( responseData . data !== this . NO_RESPONSE ) {
13191332 res . write ( responseData . data , callbackErrorWritingResponse ) ;
13201333 } else {
1321- ! res . writableEnded && res . end ( ) ;
1322- resolve ( null ) ;
1334+ endResponse ( ) ;
13231335 }
13241336 }
13251337 return await promise ;
0 commit comments