简体   繁体   中英

Node.js and https certificate error handling

To make a long story short:

I'm building node app which making a request with https (the secure version of http). Whenever I miss-configure my request options, I'm having this error:

Node.js Hostname/IP doesn't match certificate's altnames

Great... except of the fact that the entire request code is wrapped with a valid try..catch block (which works just fine.. checked that already). The code is basically something like this:

try
{
    https.request(options, (response) =>
    {
       // no way I making it so far this that error

    }).end();
}
catch(ex)
{
   // for some reason.. I'm not able to get here either
}

What I intend to do is to simply handle that error within my try..catch block

After reading some posts I've learned that this behavior is mainly because the tls module is automatically process the request and therefore making this error - this is a nice piece of information but it doesn't really help me to handle the exception.

Some other suggested to use this option:

rejectUnauthorized: false // BEWARE: security hazard!

But I rather not... so.. I guess my questions are:

  1. Handling an error with a try..catch block should work here..right?
  2. If not - is this behavior is by-design in node?
  3. Can I wrap the code in any other way to handle this error?

Just to be clear - I'm not using any third-party lib (so there is no one to blame)

Any kind of help will be appreciated

Thanks

You need to add an 'error' event handler on the request object returned by https.request() to handle that kind of error. For example:

var req = https.request(options, (response) => {
  // ...
});
req.on('error', (err) => {
  console.log('request error', err);
});
req.end();

See this section in the node.js documentation about errors for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM