Below is typescript code.
I have a for loop and its value pass to the API with url. httpservice is nestjs Httpservice.
for (const trackingCode of fileNames) {
url = url + "?trackingnumber=" + trackingCode;
var response = await this.httpService.get(url, { headers: headersRequest }).toPromise();
}
Lets imagine fileNames is below array.
fileNames = ["ABC001","ABC002"];
ABC001 code is not defined in their side and ABC002 is defined.
When starting the loop, first pass ABC001 to the API. It's throwing below error, because they doesn't has the code.
(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.
But then the loop not runs because of this error.
Then I move api calling part to separate function with error handling and call that function from main function.
async myFunc(url: string, headersRequest: any) {
try {
var response = await this.httpService.get(url, { headers: headersRequest }).toPromise();
return response;
} catch (ex) {
return null;
} finally {
}
}
Even with try catch blocks, the loop is not run further. simply when error throw because ABC001, then it will not run for ABC002.
How to handle this kind of issue? I want to remain the loop run, even if any error occurred.
EDIT
This is how I use "myFunc" in the main function.
var response = await this.myFunc(url, headersRequest);
if (response != null) {
//my logic goes here
}
question from:
https://stackoverflow.com/questions/65868872/loop-remains-run-even-if-error-occurred-in-typescript