Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try-Catch not handling errors with an https.get request in Node

I have an https.get request in Node for which I need to handle the errors - preferably in a try-catch block. For instance, when the url is incorrect

I have tried wrapping the https.get block in a try catch and I have tried handling with res.on('error'). It seems as if in both instances the error doesn't reach the error handling block.

const https = require('https');

const hitApi = () => {

    const options = {
        "hostname": "api.kanye.rest"
    };

    try {
        https.get(options, res => {

            let body = '';


            res.on('data', data => {
                body += data;
            });

            res.on('end', () => {
                body = JSON.parse(body);
                console.dir(body);
            });

        });

    } catch (error) {
        throw error;
    }
}

hitApi();

If I change the url to a nonexistent API (e.g. api.kaye.rest) I would expect to see a handled e.rror response. Instead I see 'Unhandled error event'

like image 478
coogley-bear Avatar asked Jul 03 '19 16:07

coogley-bear


People also ask

Is it good to use try catch in node JS?

It means that you should try to avoid try/catch in hot code paths. Logic/business errors in Node are usually handled with error-first callback patterns (or Promises, or similar). Generally you'd only use try/catch if you expect programmer errors (ie. bugs), and other patterns for errors you expect.

How does try catch work in node JS?

js Try Catch is an Error Handling mechanism. When a piece of code is expected to throw an error and is surrounded with try, any exceptions thrown in the piece of code could be addressed in catch block. If the error is not handled in any way, the program terminates abruptly, which is not a good thing to happen.


Video Answer


1 Answers

The reason why try...catch.. fails is that it is meant for handling synchronous errors. https.get() is asynchronous and cannot be handled with a usual try..catch..

Use req.on('error',function(e){}); to handle the error. Like so:

var https = require('https');

var options = {
  hostname: 'encrypted.google.com',
  port: 443,
  path: '/',
  method: 'GET'
};

var req = https.request(options, function(res) {
  console.log("statusCode: ", res.statusCode);
  console.log("headers: ", res.headers);

  res.on('data', function(d) {
    process.stdout.write(d);
  });
});
req.end();
// Error handled here.
req.on('error', function(e) {
  console.error(e);
});

You can read more about the same in the documentation over here

like image 140
hem Avatar answered Oct 17 '22 07:10

hem