gpt4 book ai didi

node.js - 为什么多层异步函数不能捕获 Node 中最低级别抛出的错误?

转载 作者:太空宇宙 更新时间:2023-11-04 01:32:52 25 4
gpt4 key购买 nike

我正在尝试测试某些邮件代码的故障模式,该代码在最低级别可能会引发错误。测试和抛出的函数之间的所有层都是异步的,并在它们下面的函数上使用await。在顶层(也在异步函数中,我有一个 try catch block 。但是,在错误传播到此级别之前, Node 会抛出未处理的 promise 异常。

我的测试代码如下所示

beforeEach(function() {
//set default values - tests can change them
this.reasons = '';
this.reschedules = 0;
this.params.cid = 35124;

this.startTest = async () => {
/* this.confirmation is an async function under test,
this.mailer is a mock mailer with an async "send" method
which will throw an error in the correct test */
const doner = this.confirmation(this.mailer);
// ..other actions related to mocking database access made by confirmation
await doner;
return this.mailer.maildata; //provide info on parameters passed to this.mailer
};
});
it('Failure to send is reported', async function() {
this.mailer.sendResolve = false; //tell mock mailer to fail send request
try {
await this.startTest();
expect(true).to.be.false;
} catch(err) {
expect(err).to.be.instanceOf(Error);
}
});

模拟邮件程序有点像这样

class Mailer {
constructor(user,params){
...
}
...
async send(subject, to, cc, bcc) {
this.maildata.subject = subject;
if (to !== undefined) this.maildata.to = to;
if (cc !== undefined) this.maildata.cc = cc;
if (bcc !== undefined) this.maildata.bcc = bcc;
if (!this.sendResolve) throw new Error('Test Error');
}
...
}

以及被测代码的摘要

 module.exports = async function(mailer) {
//get confirm data from database
const cData = await confirm(mailer.params.cid, mailer.db);
if (cData.count > 0) {
// ... format the email message and build it into maildata
await mailer.send(
subject,
emailAddress,
null,
process.env.PAS_MAIL_FROM,
{
pid:cData.pid,
type: 'confirmation',
extra: `Calendar ID ${mailer.params.cid} with procedure ${cData.procedure}`
}
);
debug('message sent, update the database');
await mailer.db.exec(async connection => {
...
});
debug('success');
} else {
debug('invalid calendarid');
throw new Error('Invalid Calendar ID');
}
};

可以看出,从返回堆栈的 async send 函数到 try {}catch(){} 的调用路径都是异步函数。但是当我运行这个测试 Node 时,会输出一个未处理的 promise 拒绝。

我尝试使用 Visual Studio 代码调试器单步执行此操作,但我有点迷失在包装异步函数以将其转换为 promise 提供者的机制中。据我所知,一层错误被正确处理,然后在下一层失败。

这是否意味着每个异步函数都必须有一个 try catch block 来捕获并重新抛出任何错误?我找不到任何解释说我必须这样做。

最佳答案

回答您的问题:

Does this mean that every async function must have a try catch block to catch and rethrow any error?

错误通过 await-ed 调用向上传播,如您所料:

const assert = require('assert');

const outer = async () => {
await middle();
}

const middle = async () => {
await inner();
}

const inner = async () => {
throw new Error('something bad happened');
}

it('should catch the error', async () => {
let errorMessage;
try {
await outer();
}
catch (err) {
errorMessage = err.message;
}
assert(errorMessage === 'something bad happened'); // Success!
});

...所以不,您不需要在每个级别都有 try/catch block 。

<小时/>

追踪未处理的 Promise 拒绝

我无法准确地看出示例代码中的 await 链可能在哪里被破坏,但为了帮助追踪未处理的 Promise 拒绝,您可以添加 process handler for the unhandledRejection event并查看记录的 Promise 来查看拒绝从哪里开始,并从那里向后跟踪调用堆栈:

const assert = require('assert');

const outer = async () => {
await middle();
}

const middle = async () => {
inner(); // <= this will cause an Unhandled Rejection
}

const inner = async () => {
throw new Error('something bad happened');
}

it('should catch the error', async () => {
let errorMessage;
try {
await outer();
}
catch (err) {
errorMessage = err.message;
}
assert(errorMessage === undefined); // Success! (broken await chain)
})

process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at:', p);
console.log('reason:', reason);
});

...在本例中记录:

Unhandled Rejection at: Promise {
<rejected> Error: something bad happened
at inner (.../code.test.js:12:9)
at inner (.../code.test.js:8:3)
at middle (.../code.test.js:4:9) // <= this is the broken link
at Context.outer (.../code.test.js:18:11)
at callFn (...\node_modules\mocha\lib\runnable.js:387:21)
...

...这向我们指出了 inner 中抛出的 Error,通过追踪链,我们发现 middle 是损坏的链接。

关于node.js - 为什么多层异步函数不能捕获 Node 中最低级别抛出的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55517183/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com