admin管理员组

文章数量:1334126

It seems to me that there is no way to catch a failed connect with node tls.

tls.connect(port, host, options, function(){
    // on connected
})

Since the code is async, I can't just wrap it into try catch. And I don't seem to find an event that signals a failed ECONNREFUSED condition. .html#tls_tls_connect_options_callback

Instead the process just crashes and exits. Although I was able to catch it with uncaughtException handler. But I was not able to figure out a way to recover from the error from that handler. Don't even know which connection it was that failed when program gets there.

So how do we catch a failed connect?

It seems to me that there is no way to catch a failed connect with node tls.

tls.connect(port, host, options, function(){
    // on connected
})

Since the code is async, I can't just wrap it into try catch. And I don't seem to find an event that signals a failed ECONNREFUSED condition. http://nodejs/api/tls.html#tls_tls_connect_options_callback

Instead the process just crashes and exits. Although I was able to catch it with uncaughtException handler. But I was not able to figure out a way to recover from the error from that handler. Don't even know which connection it was that failed when program gets there.

So how do we catch a failed connect?

Share Improve this question asked Jan 16, 2014 at 15:59 MartinMartin 3,6024 gold badges28 silver badges34 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 8

The tls.connect method returns a stream object that you should be binding an error handler to.

To make it clearer:

tls.connect(port, host, options, function(){
  // on connected
});

is short for this:

var stream = tls.connect(port, host, options);
stream.once('secureConnect', function(){
  // on connected
});

So you need to add another handler to listen for errors instead of successful connections:

var stream = tls.connect(port, host, options);
stream.once('secureConnect', function(){
  // on connected
});
stream.on('error', function(err){
  // on error
});

tls.connect() creates a new client connection to the given port and host. tls.connect() returns a tls.TLSSocket object.

You can use the following code to handle the error.

var options = {
host: 'example.',
port: 443
};

var socket = tls.connect(options, function() {
  // Connected
}); 
socket.on('error', function(err) {
  // on error
});

Find more information here

本文标签: javascriptNode js TLS uncaught error on connection fail How to catchStack Overflow