我正在尝试测试某些邮寄代码的故障模式,最低级别可能会引发错误。测试和抛出的函数之间的所有层都是异步的,并在它们下面的函数上使用await。在顶层(同样在异步函数中,我还有一个try catch块。但是,在错误传播到该层之前,节点抛出了未处理的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(){}
都是异步函数。但是当我运行此测试节点时,会输出未处理的承诺拒绝。
我曾尝试使用Visual Studio代码调试器来完成此步骤,但是我迷上了包装异步功能以将其转变为Promise提供程序的机制。据我所知,正确处理了一层错误,然后在下一层错误了。
这是否意味着每个异步函数都必须具有try catch块才能捕获并抛出任何错误?我找不到任何说明必须这样做的解释。
答案 0 :(得分:0)
回答您的问题:
这是否意味着每个异步函数都必须具有try catch块才能捕获并抛出任何错误?
错误通过await
版本的电话传播,如您所愿:
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
块。
跟踪未处理的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)
...
...这指向指向Error
的{{1}},通过追踪链,我们发现inner
是断开的链接。