[英]Issue with try catch in async await
I am struggling with async await try catch block for a couple of days. 我正在努力与异步等待尝试catch块几天。
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 故意改变了job.id到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.
如果有错误,则抛出新创建的自定义Error类。 But throwing QueueError will cause logging
但抛出QueueError会导致日志记录
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. 即使不需要在那里捕获错误,因为try块正在工作如果我抛出QueueError我只想在最后一个catch块中捕获错误。
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);
}
});
});
You can refactor your code in smaller functions that return a promise for which you can locally wrap try-catch and handle it. 您可以在较小的函数中重构代码,这些函数返回一个promise,您可以在本地包装try-catch并处理它。
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;
}
}
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. 我看到的唯一区别是承诺线#3的拒绝。 So I'm wondering if:
所以我想知道是否:
let destroyJobId = await app.models.Job.destroyById(job.idd);
let destroyJobId = await app.models.Job.destroyById(job.idd);
It's rejecting properly the promise. 它正确地拒绝承诺。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.