@@ -179,8 +179,15 @@ C.open = function(allFields, openCallback0) {
179179 function send ( Method ) {
180180 // This can throw an exception if there's some problem with the
181181 // options; e.g., something is a string instead of a number.
182- try { self . sendMethod ( 0 , Method , tunedOptions ) ; }
183- catch ( err ) { bail ( err ) ; }
182+ try {
183+ self . sendMethod ( 0 , Method , tunedOptions ) ;
184+ } catch ( err ) {
185+ bail ( err ) ;
186+
187+ // We are in an inconsistent state so we can't continue,
188+ // rethrowing the exception will stop further execution.
189+ throw err ;
190+ }
184191 }
185192
186193 function negotiate ( server , desired ) {
@@ -206,8 +213,13 @@ C.open = function(allFields, openCallback0) {
206213 return ;
207214 }
208215 self . serverProperties = start . fields . serverProperties ;
209- send ( defs . ConnectionStartOk ) ;
210- wait ( afterStartOk ) ;
216+ try {
217+ send ( defs . ConnectionStartOk ) ;
218+ wait ( afterStartOk ) ;
219+ } catch ( _ ) {
220+ // Exit, callback with error already called,
221+ return ;
222+ }
211223 }
212224
213225 function afterStartOk ( reply ) {
@@ -228,8 +240,13 @@ C.open = function(allFields, openCallback0) {
228240 negotiate ( fields . channelMax , allFields . channelMax ) ;
229241 tunedOptions . heartbeat =
230242 negotiate ( fields . heartbeat , allFields . heartbeat ) ;
231- send ( defs . ConnectionTuneOk ) ;
232- send ( defs . ConnectionOpen ) ;
243+ try {
244+ send ( defs . ConnectionTuneOk ) ;
245+ send ( defs . ConnectionOpen ) ;
246+ } catch ( _ ) {
247+ // Exit, callback with error already called,
248+ return ;
249+ }
233250 expect ( defs . ConnectionOpenOk , onOpenOk ) ;
234251 break ;
235252 default :
@@ -257,6 +274,10 @@ C.open = function(allFields, openCallback0) {
257274 // If the server closes the connection, it's probably because of
258275 // something we did
259276 function endWhileOpening ( err ) {
277+ self . stream . removeListener ( 'end' , endWhileOpening ) ;
278+ self . stream . removeListener ( 'error' , endWhileOpening ) ;
279+ self . stream . end ( ) ;
280+
260281 bail ( err || new Error ( 'Socket closed abruptly ' +
261282 'during opening handshake' ) ) ;
262283 }
0 commit comments