【发布时间】:2017-11-18 15:20:45
【问题描述】:
我正在使用nock.back 来模拟一些 API 调用。当进行意外调用时,UnhandledPromiseRejectionWarning 会打印到控制台,但我的测试通过了,并且这些警告很容易在控制台输出的其余部分中遗漏。我想要抛出异常而不是静默错误。我该怎么做?
【问题讨论】:
我正在使用nock.back 来模拟一些 API 调用。当进行意外调用时,UnhandledPromiseRejectionWarning 会打印到控制台,但我的测试通过了,并且这些警告很容易在控制台输出的其余部分中遗漏。我想要抛出异常而不是静默错误。我该怎么做?
【问题讨论】:
我使用 Promise 的方式是:
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)
}
)
更新
你看过这里吗? 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 在单个进程上运行。
【讨论】:
try/catch
process.exit(1),所以测试不会通过。