How can I determine what causes an UnhandledPromiseRejectionWarning in Node.js?

前端 未结 2 1394
粉色の甜心
粉色の甜心 2021-02-09 05:08

I\'ve structured my Node.js application around the async/await library and it has been working great most of the time. The only trouble I have with it is that whenever a promise

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-09 05:32

    I suggest you set a global unhandledRejection handler at the very beginning of your entry file:

    process.on('unhandledRejection', (reason, p) => { throw reason });
    

    This way, even if you forget to catch the errors locally, you can still track them down easily.

    Update

    There seems to be some confusion as to how the above handler helps you. Basically, when you don't catch promise errors, node outputs that warning to the console. For whatever silly reason, node only outputs the error message without the stack. Setting up the handler and then rethrowing the error generates the stack and allows you to debug your code easier. Here's an example:

    let test = () => new Promise((resolve, reject) => {
        throw new Error('Random Error'); // same as "reject(new Error('Random Error'));"
    });
    
    test();
    

    Without the handler you get:

    (node:20012) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Random Error
    

    Then, we add the handler at the top of our file:

    process.on('unhandledRejection', (reason, p) => { throw reason });
    
    let test = () => new Promise((resolve, reject) => {
        throw new Error('Random Error'); // same as "reject(new Error('Random Error'));"
    });
    
    test();
    

    Now we get a much nicer error stack:

    (function (exports, require, module, __filename, __dirname) { process.on('unhandledRejection', (reason, p) => { throw reason });
                                                                                                                    ^
    
    Error: Random Error
        at Promise (S:\amir\test.js:5:9)
        at test (S:\amir\test.js:3:18)
        at Object. (S:\amir\test.js:8:1)
        at Module._compile (module.js:570:32)
        at Object.Module._extensions..js (module.js:579:10)
        at Module.load (module.js:487:32)
        at tryModuleLoad (module.js:446:12)
        at Function.Module._load (module.js:438:3)
        at Module.runMain (module.js:604:10)
        at run (bootstrap_node.js:394:7)
    

提交回复
热议问题