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 (eg api.kaye.rest) I would expect to see a handled e.rror response. Instead I see 'Unhandled error event'
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
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.