【发布时间】:2019-11-14 10:09:03
【问题描述】:
我在 Node 中有一个 https.get 请求,我需要为其处理错误 - 最好是在 try-catch 块中。例如,当 url 不正确时
我尝试将 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();
如果我将 url 更改为不存在的 API(例如 api.kaye.rest),我希望看到已处理的 e.rror 响应。相反,我看到“未处理的错误事件”
【问题讨论】:
-
使用
.on('error', (e) => { console.error(e); });nodejs.org/api/https.html#https_https_get_options_callback
标签: javascript node.js https error-handling try-catch