【问题标题】:How to make node throw an error for UnhandledPromiseRejectionWarning如何使节点为 UnhandledPromiseRejectionWarning 抛出错误
【发布时间】:2017-11-18 15:20:45
【问题描述】:

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

【问题讨论】:

    标签: node.js promise nock


    【解决方案1】:

    我使用 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 在单个进程上运行。

    【讨论】:

    • 我知道这是最佳做法,但我希望我的测试在不遵循最佳做法时失败。
    • 你看过这里吗? nodejs.org/api/process.html#process_event_unhandledrejection 它描述了一个 unhandledRejection 事件,当您没有从 Promise 中捕获拒绝时会发生该事件,并为您提供基本上捕获 WARNING 的代码。
    • 第一个 sn-p 没用,你不需要在 Promise 构造函数回调中添加try/catch
    • 这已经足够接近了,我在处理程序中添加了process.exit(1),所以测试不会通过。
    猜你喜欢
    • 2020-03-24
    • 1970-01-01
    • 2021-05-13
    • 2020-09-15
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 2023-03-31
    • 2015-03-26
    相关资源
    最近更新 更多