Basically, why isn’t this exception caught?
var http = require('http'),
options = {
host: 'www.crash-boom-bang-please.com',
port: 80,
method: 'GET'
};
try {
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
throw new Error("Oh noes");
});
req.end();
} catch(_error) {
console.log("Caught the error");
}
Some people suggest that these errors need to be handled with event emitters or callback(err) (having callbacks with err, data signature isn’t something I’m used to)
What’s the best way to go about it?
When you are throwing the error the
try {}block has been long left, as the callback is invoked asynchronously outside of the try/catch. So you cannot catch it.Do whatever you want to do in case of an error inside the error callback function.