0

下面是打字稿代码。

我有一个 for 循环,它的值通过 url 传递给 API。httpservice 是nestjs 的Httpservice。

for (const trackingCode of fileNames) {
     url = url + "?trackingnumber=" + trackingCode;
     var response = await this.httpService.get(url, { headers: headersRequest }).toPromise();

}

让我们想象一下 fileNames 在数组下面。

fileNames = ["ABC001","ABC002"];

他们这边没有定义ABC001代码,定义了ABC002。

启动循环时,首先将 ABC001 传递给 API。它抛出错误,因为他们没有代码。

(node:27932) UnhandledPromiseRejectionWarning: Error: Request failed with status code 400
    at createError (/mnt/d/Freiteq/Tracking_Node/tracking/node_modules/axios/lib/core/createError.js:16:15)
    at settle (/mnt/d/Freiteq/Tracking_Node/tracking/node_modules/axios/lib/core/settle.js:17:12)
    at IncomingMessage.handleStreamEnd (/mnt/d/Freiteq/Tracking_Node/tracking/node_modules/axios/lib/adapters/http.js:237:11)
    at IncomingMessage.emit (events.js:327:22)
    at endReadableNT (_stream_readable.js:1220:12)
    at processTicksAndRejections (internal/process/task_queues.js:84:21)
(node:27932) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:27932) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

但是由于这个错误,循环没有运行。

然后我将 api 调用部分移动到带有错误处理的单独函数,并从主函数中调用该函数。

 async myFunc(url: string, headersRequest: any) {

    try {
      var response = await this.httpService.get(url, { headers: headersRequest }).toPromise();
      return response;
    } catch (ex) { 
      return null;
    } finally {
    }

  }

即使使用 try catch 块,循环也不会进一步运行。只是当因为 ABC001 引发错误时,它不会为 ABC002 运行。

如何处理此类问题?即使发生任何错误,我也想保持循环运行。

编辑

这就是我在主函数中使用“myFunc”的方式。

  var response = await this.myFunc(url, headersRequest);

  if (response != null) {
       //my logic goes here
  }
4

1 回答 1

1

我可以想到两件事,首先这行代码对我来说很可疑:

url = url + "&trackingnumber=" + trackingCode;

因为它会不断地在循环中附加更多的跟踪号码,而不是替换它。所以我预计不止一次失败。

另一方面,如果这只是示例代码,并且真正的代码运行正确,那么可能this.httpService.get是没有正确处理来自 axios 库的承诺。围绕异步代码的 try catch 无法捕获在其他库中已抛出且未正确处理的错误,例如它们未正确等待值或 .catch 未用于承诺。

于 2021-01-24T09:49:22.590 回答