我在理解此错误时遇到一些问题。我有一个名为 getDeliveryDate() 的函数,该函数是从端点调用的。这个函数似乎是非异步函数,但我收到了一个未处理的 promise 错误:
// Deadlines increments are in minutes
function getDeliveryDate(
inputDate,
normalDeadline,
fastDeadline,
fastDelivery
) {
var deliveryDate = new Date();
try {
!fastDelivery
? deliveryDate.setTime(inputDate + normalDeadline * 60 * 1000)
: deliveryDate.setTime(inputDate + fastDeadline * 60 * 1000);
return deliveryDate;
} catch (error) {
console.log("getDeliveryDate error:".error, error);// <-- this line is okey, I am using colors library
}
这就是调用 getDeliveryDate 的地方
...
try {
blockFields.finishDate = getDeliveryDate( // <-- the call
Date.now(),
req.body.blockOptions.deadline,
req.body.blockOptions.fastDeadline,
req.body.blockOptions.fastDelivery
);
} catch (error) {
console.log("getDeliveryDate error".error, error); // <-- this line is okey, I am using colors library
}
...
我缺少什么? getDeliveryDate 是异步函数吗?我该如何正确处理它的错误?
更新
我使用了一个后来修改过的变量,因此不再存在。更正错误后,我仍然不确定如何捕获此函数的错误。
现在一切正常,但如果我输入错误的变量,我仍然无法捕获错误并收到此错误(即,如果我输入错误的 finishDate 值):
( Node :50620)UnhandledPromiseRejectionWarning:ValidationError: block 验证失败:finishDate:路径“finishDate”处的值“无效日期”转换为日期失败
为什么我的 catch(error) 不起作用?
最佳答案
将 --trace-warnings
添加到启动 Node.js 的参数中。它应该向您显示未处理错误的堆栈跟踪。
但是,看起来这行 console.log("getDeliveryDate error".error, error);
可能是罪魁祸首。 catch block 中出现错误,但没有任何内容可以捕获该错误。
关于javascript - Node/Express 中非异步函数中的 UnhandledPromiseRejectionWarning,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55908623/