这些天我经常使用 async/await,但我有一个 Mocha 测试,我正在测试以确保确实抛出错误。下面您可以看到我必须捕获此错误的 try/catch block 。绿色和灰色方 block 是由 Wallaby(实时测试工具)插入的,表示从未到达 catch block 。
当我从命令行运行 mocha 时,我收到以下消息:
UnhandledPromiseRejectionWarning: FireModel::WrongRelationshipType: Can not use property "employer" on fancyperson with addToRelationship() because it is not a hasMany relationship [ relType: ownedBy, inverse: undefined ]. If you are working with a ownedBy relationship then you should instead use setRelationship() and clearRelationship().
addToRelationship() 的第一行检查关系类型是否正确(不正确)并抛出错误:
_errorIfNotHasManyReln
方法相当平淡,但为了完整起见,这里是:
protected _errorIfNotHasManyReln(
property: Extract<keyof T, string>,
fn: string
) {
if (this.META.property(property).relType !== "hasMany") {
const e = new Error(
`Can not use property "${property}" on ${
this.modelName
} with ${fn}() because it is not a hasMany relationship [ relType: ${
this.META.property(property).relType
}, inverse: ${
this.META.property(property).inverse
} ]. If you are working with a ownedBy relationship then you should instead use setRelationship() and clearRelationship().`
);
e.name = "FireModel::WrongRelationshipType";
throw e;
}
有人可以帮我确定为什么这个错误没有被捕获吗?无奈之下,我在调用 _errorIfNotHasManyreln
的调用周围添加了另一个 try/catch block ,它确实捕获了错误,但随后我尝试重新抛出它,并再次陷入相同的情况。
最佳答案
您的 addToRelationship 方法也是异步的。您还必须等待
promise 响应:
try {
await bob.addToRelationship("employer", "4567");
}
catch(e) {
[...]
}
如果没有延迟到 promise 拒绝,则 try/catch 不会收到任何同步和终止的内容。然后发生了异常,显然没有被捕获。
关于javascript - Mocha 测试提示未处理的 Promise,但使用带有 catch block 的 async/await,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50974279/