我在Node中有一个https.get请求,我需要处理该错误-最好在try-catch块中。例如,当网址不正确
我尝试将https.get块包装在try catch中,并尝试使用res.on('error')处理。似乎在两种情况下,错误都没有到达错误处理块。
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();
如果我将网址更改为不存在的API(例如api.kaye.rest),则希望看到已处理的e.rror响应。相反,我看到“未处理的错误事件”
答案 0 :(得分:0)
try ... catch ..失败的原因是它旨在处理同步错误。 https.get()
是异步,无法通过通常的try..catch ..
使用req.on('error',function(e){});
处理错误。像这样:
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);
});
您可以在here
的文档中详细了解相同内容