我可以通过在Promise中抛出异常来中断Javascript吗?未处理的PromiseRejectionWarning



我有一个使用NodeJS和Express运行的简单Web应用程序。它有一个外部第三方可以向我们发送XML文档的途径,然后我们将其转换为JSON,然后保存到MongoDB数据库中。有几件事可能会出错:

XML可能是格式错误的

请求可能为空

外部第三方可能会向我们发送重复文件

我不想有一系列的then((块,越来越深,缩进越来越远,而是想为每个可能的错误抛出一个异常,然后在顶级捕获这些错误并在那里处理它们。

因此,我们找到一个唯一的id,然后检查这个唯一的id是否已经在MongoDB中:

// will throw an error if there is a duplicate
document_is_redundant(AMS_945, unique_id);

功能如下:

function document_is_redundant(this_model, this_unique_id) {
return this_model.findOne({ unique_id : this_unique_id })
.exec()
.then((found_document) => {
// 2021-11-28 -- if we find a duplicate, we throw an error and handle it at the end
// But remember, we want to return a HTTP status code 200 to AMS, so they will stop
// re-sending this XML document.
if (found_document != 'null') {
throw new DocumentIsRedundantException(this_unique_id);
}
});
// no catch() block because we want the exception to go to the top level
}

这给了我:UnhandledPromiseRejectionWarning

也许我想的太像Java而不是Javascript了,但我假设如果我没有捕捉到该函数中的异常((,它会冒泡到顶层,这就是我想要处理它的地方。我还假设它会在我调用该函数的那一行中断代码流。

遗憾的是,未捕获的异常不会中断执行的主线程,因此即使文档是重复的,它也会被保存。

所以我想,我能做到这一点的唯一方法是从函数返回Promise,然后在调用document_is_duplicate函数后有一个then((块?

我不喜欢把then((块嵌套在then(((块中,有好几个层次深。这似乎是错误的代码。还有别的办法吗?

如果文档存在,不确定为什么要抛出错误。查找它,Mongoose将返回一个文档(如果存在(,或者返回null(如果不存在(。然后简单地将结果await。Mongoose方法可以等待,如果你添加.exec(),它们甚至会返回一个真正的Promise,这会让你的生活更加轻松:

const document_is_redundant = (this_model, unique_id) => this_model.findOne({ unique_id }).lean().exec();
// Now you use it this way
if( !(await document_is_redundant(AMS_945, unique_id))){ // If the returned value is not null
console.log("Document is redundant! Aborting")
return;
}
// Returned value was null
console.log("The document doesn't exist yet!")

最新更新