@@ -71,6 +71,10 @@ const {
7171} = require ( 'internal/errors' ) ;
7272const { validateString } = require ( 'internal/validators' ) ;
7373const { isUint8Array } = require ( 'internal/util/types' ) ;
74+ const {
75+ defaultTriggerAsyncIdScope,
76+ symbols : { async_id_symbol }
77+ } = require ( 'internal/async_hooks' ) ;
7478
7579const HIGH_WATER_MARK = getDefaultHighWaterMark ( ) ;
7680const { CRLF , debug } = common ;
@@ -308,7 +312,6 @@ OutgoingMessage.prototype.destroy = function destroy(error) {
308312 return this ;
309313} ;
310314
311-
312315// This abstract either writing directly to the socket or buffering it.
313316OutgoingMessage . prototype . _send = function _send ( data , encoding , callback ) {
314317 // This is a shameful hack to get the headers and first body chunk onto
@@ -713,7 +716,11 @@ function write_(msg, chunk, encoding, callback, fromEnd) {
713716 }
714717
715718 if ( err ) {
716- process . nextTick ( callback , err ) ;
719+ if ( ! msg . destroyed ) {
720+ onError ( msg , err , callback ) ;
721+ } else {
722+ process . nextTick ( callback , err ) ;
723+ }
717724 msg . destroy ( err ) ;
718725 return false ;
719726 }
@@ -789,6 +796,23 @@ function onFinish(err) {
789796 this . emit ( 'finish' ) ;
790797}
791798
799+ function onError ( msg , err , callback ) {
800+ const triggerAsyncId = msg . socket ? msg . socket [ async_id_symbol ] : undefined ;
801+ defaultTriggerAsyncIdScope ( triggerAsyncId ,
802+ process . nextTick ,
803+ emitErrorNt ,
804+ msg ,
805+ err ,
806+ callback ) ;
807+ }
808+
809+ function emitErrorNt ( msg , err , callback ) {
810+ callback ?. ( err ) ;
811+ if ( typeof msg . emit === 'function' && ! msg . _closed ) {
812+ msg . emit ( 'error' , err ) ;
813+ }
814+ }
815+
792816OutgoingMessage . prototype . end = function end ( chunk , encoding , cb ) {
793817 if ( typeof chunk === 'function' ) {
794818 cb = chunk ;
@@ -799,16 +823,25 @@ OutgoingMessage.prototype.end = function end(chunk, encoding, cb) {
799823 encoding = null ;
800824 }
801825
802- if ( this . socket ) {
803- this . socket . cork ( ) ;
804- }
826+ if ( chunk !== null && chunk !== undefined ) {
827+ if ( this . finished ) {
828+ onError ( this , new ERR_STREAM_WRITE_AFTER_END ( ) , cb ) ;
829+ return this ;
830+ }
805831
806- if ( chunk !== null && chunk !== undefined )
807- this . write ( chunk , encoding ) ;
832+ if ( this . socket ) {
833+ this . socket ?. cork ( ) ;
834+ }
835+
836+ write_ ( this , chunk , encoding , null , true ) ;
837+ }
808838
809839 let err ;
810840 if ( ! this . finished ) {
811841 if ( ! this . _header ) {
842+ if ( this . socket ) {
843+ this . socket . cork ( ) ;
844+ }
812845 this . _contentLength = 0 ;
813846 this . _implicitHeader ( ) ;
814847 }
0 commit comments