【问题标题】:Try-Catch not handling errors with an https.get request in NodeTry-Catch 不处理 Node 中 https.get 请求的错误
【发布时间】: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 响应。相反,我看到“未处理的错误事件”

【问题讨论】:

标签: javascript node.js https error-handling try-catch


【解决方案1】:

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 上的文档中阅读更多相关信息

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-27
    • 2014-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-29
    相关资源
    最近更新 更多