【问题标题】:Try is executing but catch is not caching the errorTry 正在执行,但 catch 没有缓存错误
【发布时间】:2019-01-05 07:38:31
【问题描述】:

我正在尝试测试 https 连接。 “try”正在执行,但“catch”没有缓存错误并按需要执行代码。

我正在使用 node.js

var https = require("https");

  try {

  https.get({host:'nonsecuredomain.com'}, function(res){});

  }

  catch(err) {

  console.log('maybe an ssl error');

  }

events.js:167 投掷者; // 未处理的“错误”事件 ^

Error: certificate has expired
    at TLSSocket.onConnectSecure (_tls_wrap.js:1049:34)
    at TLSSocket.emit (events.js:182:13)
    at TLSSocket._finishInit (_tls_wrap.js:631:8)
Emitted 'error' event at:
    at TLSSocket.socketErrorListener (_http_client.js:392:9)
    at TLSSocket.emit (events.js:182:13)
    at emitErrorNT (internal/streams/destroy.js:82:8)
    at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
    at process._tickCallback (internal/process/next_tick.js:63:19)

【问题讨论】:

  • 可能是因为它是异步的。
  • 对 https.get 的调用不会失败 - 因此 catch 块不会拾取它。您需要查看返回到您的空回调函数 function(res){}) 的响应,

标签: javascript


【解决方案1】:

https.get 是异步的。这意味着带有try catch 的函数将在网络返回结果或错误时已经返回。

get 返回一个对象,该对象将在错误时发出事件。您应该监听那个“错误”事件并处理在那里异步抛出的错误:

https.get(url, (res) => {
    res.on('data', (d) => {
       // do stuff
    });
}).on('error', (e) => {
    console.error(e); // deal with errors
});

【讨论】:

    【解决方案2】:

    正如 taplar 所说,错误发生在其他线程上,您无法在原始线程上捕获它。

    通常异步函数返回一个promise,你可以通过 asyncFunc().catch(err => console.error(err. message))

    但是在这种情况下,异步函数返回一个事件,所以你需要这样处理它

    https.get({host:'foo.bar'}, function onSuccess(res){
        res.on('error', (e) => {
            console.error(`Got error: ${e.message}`)
        })
    }).on('error', (e) => {
        console.error(`Got error: ${e.message}`)
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多