@@ -97,15 +97,19 @@ module.exports = {
97
97
stream : function stream ( req , res , options , _ , server , clb ) {
98
98
99
99
// And we begin!
100
- server . emit ( 'start' , req , res , options . target )
100
+ server . emit ( 'start' , req , res , options . target || options . forward ) ;
101
+
101
102
if ( options . forward ) {
102
103
// If forward enable, so just pipe the request
103
104
var forwardReq = ( options . forward . protocol === 'https:' ? https : http ) . request (
104
105
common . setupOutgoing ( options . ssl || { } , options , req , 'forward' )
105
106
) ;
106
107
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 ) ;
109
113
110
114
( options . buffer || req ) . pipe ( forwardReq ) ;
111
115
if ( ! options . target ) { return res . end ( ) ; }
@@ -134,22 +138,23 @@ module.exports = {
134
138
proxyReq . abort ( ) ;
135
139
} ) ;
136
140
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 ) ;
138
143
req . on ( 'error' , proxyError ) ;
139
-
140
- // Error Handler
141
144
proxyReq . on ( 'error' , proxyError ) ;
142
145
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
+ }
153
158
}
154
159
}
155
160
0 commit comments