Reputation: 724
I am struggling with async await try catch block for a couple of days.
async function executeJob(job) {
// necessary variable declaration code here
try {
do {
let procedureRequests = await ProcedureRequestModel.find(filter, options);
// doing process here...
} while (fetchedCount < totalCount);
providerNPIIds = [...providerNPIIds];
// Fetch provider details
let providerDetails = await esHelper.getProvidersById(providerNPIIds, true);
try {
let updateProviderCount = await UserProvider.updateAll(
{
userId: userId
},
{
providers: providerNPIIds,
countByType: providerCountType
});
if(updateProviderCount) {
try {
let destroyJobId = await app.models.Job.destroyById(job.idd);
} catch (e) {
var err = new QueueError();
console.log(err instanceof QueueError);
throw new QueueError();
}
}
} catch (e) {
logger.error('Failed to update UserProviders & Count: %O', err);
throw e;
}
executeNextJob();
} catch (e) {
if(e instanceof QueueError) {
console.log('Exiting from process');
process.exit(1);
} else {
console.log('Working Code');
buryFailedJobAndExecuteNext(job);
}
}
}
Is my try catch in this async function proper?
This is how I created Custom Error Class and exported globally.
// error.js file
class QueueError extends Error {
}
global.QueueError = QueueError;
The requirement:
Intentionally changed job.id to job.idd in
let destroyJobId = await app.models.Job.destroyById(job.idd);
so that I can catch error. If there is error then throw newly created custom Error class. But throwing QueueError will cause logging
logger.error('Failed to update UserProviders & Count: %O', err);
too , even though no need to catch error there, since try block is working If I throw QueueError I only wants to catch error in last catch block only.
Below is the callback version, I am converting it into async await.
Updating providersNPIId & category count
UserProvider.updateAll({userId: userId},
{
providers: providerNPIIds,
countByType: providerCountType,
}, function(err, data) {
if (err) {
logger.error('Failed to update UserProviders & Count: %O', err);
// throw new QueueError();
}
// Remove countProvider Job
app.models.Job.destroyById(job.id, function(err) {
if (err) {
logger.error('Failed to remove countProvider job: %O', err);
}
});
});
Upvotes: 3
Views: 314
Reputation: 5853
You can refactor your code in smaller functions that return a promise for which you can locally wrap try-catch and handle it.
async function executeJob(job) {
// necessary variable declaration code here
try {
await doProcedure();
providerNPIIds = [...providerNPIIds];
// Fetch provider details
let providerDetails = await esHelper.getProvidersById(providerNPIIds, true);
const updateProviderCount = await getProviderCount(userId, providerNPIIds, providerCountType);
if(updateProviderCount) {
await destroyJobById(job.idd);
}
executeNextJob();
} catch (e) {
if(e instanceof QueueError) {
console.log('Exiting from process');
process.exit(1);
} else {
console.log('Working Code');
buryFailedJobAndExecuteNext(job);
}
}
}
async function doProcedure() {
try {
do {
let procedureRequests = await ProcedureRequestModel.find(filter, options);
// doing process here...
} while (fetchedCount < totalCount);
} catch (err) {
throw err;
}
}
async function getProviderCount(userId, providerNPIIds, providerCountType) {
try {
let updateProviderCount = await UserProvider.updateAll({ userId: userId }, { providers: providerNPIIds, countByType: providerCountType });
return updateProviderCount;
} catch (err) {
logger.error('Failed to update UserProviders & Count: %O', err);
throw e;
}
}
async function destroyJobById(Id) {
try {
let destroyJobId = await app.models.Job.destroyById(Id);
} catch (err) {
throw err;
}
}
Upvotes: 1
Reputation: 60
This is basically the same what You have:
1 function myFunctionPromise() {
2 return new Promise((response, reject) => {
3 setTimeout(() => reject("Reject Err"), 3000);
4 });
5 }
7 async function myFunction() {
8 try {
9 try {
10 await myFunctionPromise();
11 } catch(e) {
12 console.log("Second Err");
13 throw e;
14 }
15
16 } catch (e) {
17 throw e;
18 }
19
20 console.log("test");
21 }
22
23
24 myFunction()
The only difference I see it's the Reject of the promise line #3. So I'm wondering if:
let destroyJobId = await app.models.Job.destroyById(job.idd);
It's rejecting properly the promise.
Upvotes: 0