Pat*_*ors 3 node.js promise async-await
我围绕async/await库构建了我的Node.js应用程序,并且它在大多数情况下都运行良好.我遇到的唯一麻烦是,无论何时未履行承诺,我都会得到以下错误的一些变化:
(node:83333) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: Cannot read property '_id' of null
Run Code Online (Sandbox Code Playgroud)
我通常能够找到违规的承诺,但有时需要进行相当多的调试.有没有一种方法可以用来检查未处理的承诺的行号?会给我带来相当大的麻烦.
警告是由您的一个承诺中发生错误引起的,但您没有处理它,这意味着您的承诺不会catch
像您正在处理的那样处理then
.
它只是一个很好的做法来处理承诺catch
以及你正在做的事情,then
所以无论你需要记住什么情况来处理错误,即使你100%确定这个承诺不会导致错误.
这将为您提供更好,更快的方式来调试任何问题....所以对于任何承诺只需处理该catch
示例
promise.then((result)=>{
//Do something here
} , (error) =>{
//Handle promise rejection
}).catch((err) => {
//Handle error here, lets say for example, this promise is just updating user
//console.log("update user error")
//console.log(err); to be able to understand what is the error
})
Run Code Online (Sandbox Code Playgroud)
因此,如果您使用上述方式处理任何承诺...您将能够知道您的错误究竟在哪里...
我通常做的一件事就是在错误console.log
之前承诺正在做什么console.log
,正如你在上面的代码中看到的那样我正在考虑这个承诺只是更新用户...所以我在catch中提到"更新用户错误"
现在您知道此错误在更新用户承诺中
我建议您在条目文件的开始处设置一个全局unhandledRejection
处理程序:
process.on('unhandledRejection', (reason, p) => { throw reason });
Run Code Online (Sandbox Code Playgroud)
这样,即使您忘记在本地捕获错误,仍然可以轻松地找到它们。
更新资料
上面的处理程序如何帮助您似乎有些困惑。基本上,当您未捕获承诺错误时,节点会将警告输出到控制台。出于任何愚蠢的原因,节点仅输出错误消息而没有堆栈。设置处理程序,然后重新引发错误,将生成堆栈,并使您可以更轻松地调试代码。这是一个例子:
let test = () => new Promise((resolve, reject) => {
throw new Error('Random Error'); // same as "reject(new Error('Random Error'));"
});
test();
Run Code Online (Sandbox Code Playgroud)
没有处理程序,您将得到:
(node:20012) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Random Error
Run Code Online (Sandbox Code Playgroud)
然后,将处理程序添加到文件顶部:
process.on('unhandledRejection', (reason, p) => { throw reason });
let test = () => new Promise((resolve, reject) => {
throw new Error('Random Error'); // same as "reject(new Error('Random Error'));"
});
test();
Run Code Online (Sandbox Code Playgroud)
现在我们得到了一个更好的错误堆栈:
(function (exports, require, module, __filename, __dirname) { process.on('unhandledRejection', (reason, p) => { throw reason });
^
Error: Random Error
at Promise (S:\amir\test.js:5:9)
at test (S:\amir\test.js:3:18)
at Object.<anonymous> (S:\amir\test.js:8:1)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:394:7)
Run Code Online (Sandbox Code Playgroud)