我正在使用 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 事件,并提供捕获警告并将其很好地输出到控制台的代码。
(复制粘贴)
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 在单个进程上运行。
关于node.js - 如何使 Node 抛出 UnhandledPromiseRejectionWarning 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44579223/