我nock.back
用来模拟一些 API 调用。当进行意外调用时,UnhandledPromiseRejectionWarning
会打印到控制台,但我的测试通过了,并且这些警告很容易在控制台输出的其余部分中遗漏。我想要抛出异常而不是静默错误。我该怎么做呢?
问问题
2808 次
1 回答
4
我使用承诺的方式是:
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 它描述了一个 unhandledRejection 事件,当你没有捕获到来自 Promise 的拒绝时,它提供了捕获 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 在单个进程上运行。
于 2017-06-16T01:29:28.380 回答