@@ -71,6 +71,10 @@ const {
71
71
} = require ( 'internal/errors' ) ;
72
72
const { validateString } = require ( 'internal/validators' ) ;
73
73
const { isUint8Array } = require ( 'internal/util/types' ) ;
74
+ const {
75
+ defaultTriggerAsyncIdScope,
76
+ symbols : { async_id_symbol }
77
+ } = require ( 'internal/async_hooks' ) ;
74
78
75
79
const HIGH_WATER_MARK = getDefaultHighWaterMark ( ) ;
76
80
const { CRLF , debug } = common ;
@@ -308,7 +312,6 @@ OutgoingMessage.prototype.destroy = function destroy(error) {
308
312
return this ;
309
313
} ;
310
314
311
-
312
315
// This abstract either writing directly to the socket or buffering it.
313
316
OutgoingMessage . prototype . _send = function _send ( data , encoding , callback ) {
314
317
// 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) {
713
716
}
714
717
715
718
if ( err ) {
716
- process . nextTick ( callback , err ) ;
719
+ if ( ! msg . destroyed ) {
720
+ onError ( msg , err , callback ) ;
721
+ } else {
722
+ process . nextTick ( callback , err ) ;
723
+ }
717
724
msg . destroy ( err ) ;
718
725
return false ;
719
726
}
@@ -789,6 +796,23 @@ function onFinish(err) {
789
796
this . emit ( 'finish' ) ;
790
797
}
791
798
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
+
792
816
OutgoingMessage . prototype . end = function end ( chunk , encoding , cb ) {
793
817
if ( typeof chunk === 'function' ) {
794
818
cb = chunk ;
@@ -799,16 +823,25 @@ OutgoingMessage.prototype.end = function end(chunk, encoding, cb) {
799
823
encoding = null ;
800
824
}
801
825
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
+ }
805
831
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
+ }
808
838
809
839
let err ;
810
840
if ( ! this . finished ) {
811
841
if ( ! this . _header ) {
842
+ if ( this . socket ) {
843
+ this . socket . cork ( ) ;
844
+ }
812
845
this . _contentLength = 0 ;
813
846
this . _implicitHeader ( ) ;
814
847
}
0 commit comments