I've faced the problem of catching errors in an infinite while-loop. So i want my code to exit node.js with proccess.exit(-1) if there's some errors cathed in the loop. So here's the code:
while (true) {
await promisifiedDelay(20000);
users.map(async (client) => {
//await client.login();
const allRequests = await client.getFollowRequests();
const requests = allRequests.slice(0, 100);
const currentName = await client.getCurUsername();
if (requests.length) {
console.log(`${currentName}: `, requests);
}
requests.map(async (request) => {
await promisifiedDelay(500);
await client.approve({ userId: request.node.id });
})
await updateAdded(requests.length, currentName);
});
}
Could u recommend please the best way to catch all errors in the loop?
You can wrap your block in a try catch
:
while (true) {
try {
await promisifiedDelay(20000);
users.map(async client => {
//await client.login();
const allRequests = await client.getFollowRequests();
const requests = allRequests.slice(0, 100);
const currentName = await client.getCurUsername();
if (requests.length) {
console.log(`${currentName}: `, requests);
}
requests.map(async request => {
await promisifiedDelay(500);
await client.approve({ userId: request.node.id });
});
await updateAdded(requests.length, currentName);
});
} catch (e) {
console.log(e);
break; // or process.exit(-1)
}
}
Use this example:
while (true) {
try {
await promisifiedDelay(20000).catch(err => throw err);
users.map(async (client) => {
//await client.login();
const allRequests = await client.getFollowRequests().catch(err => throw err);
const requests = allRequests.slice(0, 100);
const currentName = await client.getCurUsername().catch(err => throw err);
if (requests.length) {
console.log(`${currentName}: `, requests);
}
requests.map(async (request) => {
await promisifiedDelay(500).catch(err => throw err);
await client.approve({ userId: request.node.id }).catch(err => throw err);
})
await updateAdded(requests.length, currentName);
});
} catch(error) {
console.log(error);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.