[英]How to handle `UnhandledPromiseRejectionWarning`
I have await
statements which can throw errors so I am executing them inside a try/catch
. 我有一个await
语句,它可能引发错误,所以我在try/catch
执行它们。 However the try/catch
is not catching them I get warnings: 但是try/catch
没有捕获它们,我得到警告:
(node:4496) UnhandledPromiseRejectionWarning: Error: Request timed out. (节点:4496)UnhandledPromiseRejectionWarning:错误:请求超时。
My code is: 我的代码是:
(async() => {
try
{
const result_node = nodeClient.getInfo();
}
catch (e)
{
console.error("Error connecting to node: " + e.stack);
}
})();
I have also tried using wait-to-js
. 我也尝试过使用wait-to-js
。 Although it catches the error I still get the error in stderr. 尽管它捕获了错误,但在stderr中仍然出现错误。
(async() => {
try
{
const [err_node, result_node] = await to(nodeClient.getInfo());
if(err_node)
console.error("Could not connect to the Node");
}
catch (e)
{
console.error("Error connecting to node: " + e.stack);
}
})();
What is the right way to handle errors with async/await
? 用async/await
处理错误的正确方法是什么? Thank you. 谢谢。
You need to use the await
keyword when you are waiting for an async call to return. 等待异步调用返回时,需要使用await
关键字。
(async() => {
try
{
const result_node = await nodeClient.getInfo(); // <- await keyword before the function call
}
catch (e)
{
console.error("Error connecting to node: " + e.stack);
}
})();
try this 尝试这个
(async() => {
try{
const result_node = await nodeClient.getInfo();
}catch (e){
console.error("Error connecting to node: " + e.stack);
}
})();
correct process to use async await is 使用异步等待的正确过程是
var functionName = async() => {
try
{
const result_node = await nodeClient.getInfo();
}
catch (e)
{
console.error("Error connecting to node: " + e);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.