如何使节点为UnhandledPromiseRejectionWarning抛出错误

时间:2017-06-16 01:01:46

标签: node.js promise nock

我正在使用nock.back来模拟一些API调用。当发出意外调用时,UnhandledPromiseRejectionWarning将被打印到控制台,但我的测试通过,并且在控制台输出的其余部分中很容易错过这些警告。我想要抛出异常而不是静默错误。我该怎么做?

1 个答案:

答案 0 :(得分:2)

我使用承诺的方式是:

function myFunction(){
   return new Promise((resolve, reject) -> {
       try {
           // Logic
           resolve(logic)
       } catch(e) {
           reject('Provide your error message here -> ' + e)
       }
   })
}

或者!

function myFunction().then( // Calls the function defined previously
    logic => { // Instead of logic you can write any other suitable variable name for success
        console.log('Success case')     
    }, 
    error => {
        console.log('myFunction() returned an error: ' + error)
    }
)

UPD

你在这看过吗? https://nodejs.org/api/process.html#process_event_unhandledrejection 它描述了当你没有捕获来自Promise的拒绝时发出的unhandledRejection事件,并提供代码来捕获WARNING并将其很好地输出到控制台。

(复制粘贴)

process.on('unhandledRejection', (reason, p) => {
   console.log('Unhandled Rejection at:', p, 'reason:', reason);
   // application specific logging, throwing an error, or other logic here
});

Node.js在单个进程上运行。

相关问题