【问题标题】:Proper way to handle fetch errors in NodeJS v18?处理 NodeJS v18 中获取错误的正确方法?
【发布时间】:2022-12-31 01:04:15
【问题描述】:

我切换到带有内置 fetch 的 NodeJS v18,我这样使用它:

async function get511AK() {
    let res = await fetch(URL, { method: 'GET' })
    if (res.ok && (res.headers.get('content-type').includes('json'))) {
        let data = await res.json();
        jsonresponseAK = data;
    } else {
        console.log("(" + res.url + ') is not json');
    }
}

但是,有时我会在 URL 上遇到超时,这种情况会发生,但会导致脚本退出。我试过将它包装在 try/catch 中,但并没有阻止它退出。 这在 node-fetch 库下的 Node v12 中从未发生过。我还可以添加什么来控制这些连接超时?

node:internal/deps/undici/undici:11118
    Error.captureStackTrace(err, this);
          ^

TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:11118:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Timeout.get511AK [as _onTimeout] (/home/wazebot/dot-scripts/script-relay.js:76:12) {
  cause: ConnectTimeoutError: Connect Timeout Error
      at onConnectTimeout (node:internal/deps/undici/undici:6625:28)
      at node:internal/deps/undici/undici:6583:50
      at Immediate._onImmediate (node:internal/deps/undici/undici:6614:13)
      at process.processImmediate (node:internal/timers:471:21) {
    code: 'UND_ERR_CONNECT_TIMEOUT'
  }
}

Node.js v18.12.1

【问题讨论】:

    标签: node.js fetch


    【解决方案1】:

    希望它有所帮助!

    process.on('uncaughtException', console.log);
    //  Uncaught Exception thrown - when you throw an error and did not catch anywhere.
    
    process.on('unhandledRejection', console.log);
    // Unhandled Rejection at Promise - similar, when you fail to catch a Promise.reject.
    

    【讨论】:

      猜你喜欢
      • 2021-06-16
      • 2012-05-15
      • 2012-10-06
      • 2019-05-17
      • 1970-01-01
      • 2019-02-01
      • 1970-01-01
      • 2019-03-04
      • 1970-01-01
      相关资源
      最近更新 更多