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'
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With