异步等待中的 try catch 问题
Issue with try catch in async await
几天来我一直在努力处理 async await try 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);
}
}
}
我在这个异步函数中的 try catch 是否正确?
这就是我创建自定义错误 Class 并导出到全球的方式。
// error.js file
class QueueError extends Error {
}
global.QueueError = QueueError;
要求:
在
中有意将 job.id 更改为 job.idd
let destroyJobId = await app.models.Job.destroyById(job.idd);
这样我就可以发现错误。
如果有错误,则抛出新创建的自定义错误 class。但是抛出 QueueError 会导致日志记录
logger.error('Failed to update UserProviders & Count: %O', err);
也是,尽管不需要在那里捕获错误,因为 try 块正在工作
如果我抛出 QueueError,我只想在最后一个 catch 块中捕获错误。
下面是回调版本,我正在把它转换成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);
}
});
});
您可以在更小的函数中重构您的代码,return 您可以在本地包装 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;
}
}
这与您所拥有的基本相同:
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()
我看到的唯一区别是承诺行 #3 的拒绝。所以我想知道是否:
let destroyJobId = await app.models.Job.destroyById(job.idd);
它正在妥善拒绝承诺。
几天来我一直在努力处理 async await try 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);
}
}
}
我在这个异步函数中的 try catch 是否正确?
这就是我创建自定义错误 Class 并导出到全球的方式。
// error.js file
class QueueError extends Error {
}
global.QueueError = QueueError;
要求:
在
中有意将 job.id 更改为 job.iddlet destroyJobId = await app.models.Job.destroyById(job.idd);
这样我就可以发现错误。 如果有错误,则抛出新创建的自定义错误 class。但是抛出 QueueError 会导致日志记录
logger.error('Failed to update UserProviders & Count: %O', err);
也是,尽管不需要在那里捕获错误,因为 try 块正在工作 如果我抛出 QueueError,我只想在最后一个 catch 块中捕获错误。
下面是回调版本,我正在把它转换成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);
}
});
});
您可以在更小的函数中重构您的代码,return 您可以在本地包装 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;
}
}
这与您所拥有的基本相同:
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()
我看到的唯一区别是承诺行 #3 的拒绝。所以我想知道是否:
let destroyJobId = await app.models.Job.destroyById(job.idd);
它正在妥善拒绝承诺。