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

前端 未结 2 1396
粉色の甜心
粉色の甜心 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:36

    The warning is caused by a an error happened in one of your promises, but you are not handling it, this means your promise is not handling the catch as well as you are handling then.

    Its just a good practice to handle promise catch as well as you are doing with then so no matter what is the situation you need to keep in mind to handle errors even if you are 100% sure this promise will not cause an error.

    This will give you a better and faster way to debug any issue .... so for any promise just handle the catch example

    promise.then((result)=>{
       //Do something here
    } ,  (error) =>{
       //Handle promise rejection
    }).catch((err) => {
       //Handle error here, lets say for example, this promise is just updating user
       //console.log("update user error") 
       //console.log(err); to be able to understand what is the error
    })
    

    So if you used the above way to handle any promise ... you will be able to know where exactly is your error ...

    Also one thing that i usually do is to console.log what the promise is doing before console.log the error, as you can see in the code above i am considering that this promise is just updating a user ... so i mention in the catch "update user error"

    Now you know this error is inside the update user promise

提交回复
热议问题