在NodeJS v18中处理获取错误的正确方法是什么?

olhwl3o2  于 2023-01-01  发布在  Node.js
关注(0)|答案(1)|浏览(287)

我切换到NodeJS v18,使用内置的fetch,我使用它如下:

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中,但它没有阻止脚本退出。这种情况从未在节点获取库下的节点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
laik7k3q

laik7k3q1#

希望它有帮助!

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.

相关问题