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);
}
});
});