@@ -97,15 +97,19 @@ module.exports = {
9797 stream : function stream ( req , res , options , _ , server , clb ) {
9898
9999 // And we begin!
100- server . emit ( 'start' , req , res , options . target )
100+ server . emit ( 'start' , req , res , options . target || options . forward ) ;
101+
101102 if ( options . forward ) {
102103 // If forward enable, so just pipe the request
103104 var forwardReq = ( options . forward . protocol === 'https:' ? https : http ) . request (
104105 common . setupOutgoing ( options . ssl || { } , options , req , 'forward' )
105106 ) ;
106107
107- // error handler (e.g. ECONNREFUSED)
108- forwardReq . on ( 'error' , proxyError ) ;
108+ // error handler (e.g. ECONNRESET, ECONNREFUSED)
109+ // Handle errors on incoming request as well as it makes sense to
110+ var forwardError = createErrorHandler ( forwardReq , options . forward ) ;
111+ req . on ( 'error' , forwardError ) ;
112+ forwardReq . on ( 'error' , forwardError ) ;
109113
110114 ( options . buffer || req ) . pipe ( forwardReq ) ;
111115 if ( ! options . target ) { return res . end ( ) ; }
@@ -134,22 +138,23 @@ module.exports = {
134138 proxyReq . abort ( ) ;
135139 } ) ;
136140
137- // Handle errors on incoming request as well as it makes sense to
141+ // handle errors in proxy and incoming request, just like for forward proxy
142+ var proxyError = createErrorHandler ( proxyReq , options . target ) ;
138143 req . on ( 'error' , proxyError ) ;
139-
140- // Error Handler
141144 proxyReq . on ( 'error' , proxyError ) ;
142145
143- function proxyError ( err ) {
144- if ( req . socket . destroyed && err . code === 'ECONNRESET' ) {
145- server . emit ( 'econnreset' , err , req , res , options . target || options . forward ) ;
146- return proxyReq . abort ( ) ;
147- }
148-
149- if ( clb ) {
150- clb ( err , req , res , options . target ) ;
151- } else {
152- server . emit ( 'error' , err , req , res , options . target ) ;
146+ function createErrorHandler ( proxyReq , url ) {
147+ return function proxyError ( err ) {
148+ if ( req . socket . destroyed && err . code === 'ECONNRESET' ) {
149+ server . emit ( 'econnreset' , err , req , res , url ) ;
150+ return proxyReq . abort ( ) ;
151+ }
152+
153+ if ( clb ) {
154+ clb ( err , req , res , url ) ;
155+ } else {
156+ server . emit ( 'error' , err , req , res , url ) ;
157+ }
153158 }
154159 }
155160
0 commit comments