Error in ASYNC update method with Node.js

Asked

Viewed 186 times

-1

Unhandledpromiserejectionwarning: Unhandled Promise rejection. This error either originated by Throwing Inside of an async Function without a catch block, or by rejecting a Promise which was not handled with . catch().

when I try to run the async Node update method, I get this error message

  • Put the code in the question

1 answer

3

This message means you have a Promise, which was rejected(an error occurred) and this error was not treated.

If you are dealing with Promises through functions async, you must add a Try...catch to capture the error of the function you called; and you need to treat this error.

Examples of how you might have received this error, given the function:

async function ruim() {
    throw new Error('Ops');
}

Erro1 - do not treat:

In the code below the error is not treated:

async function errado1(){
    await ruim();
}
errado1();

Erro2 - do not wait:

In the code below is not waiting for the execution of async function, then the error is not captured:

async function errado2(){
    try{
        ruim();
    } catch(e) {
      console.log('ocorreu um erro: ' + e);  
    }
}
errado2();

Correct:

async function correto(){
    try{
        await ruim();
    } catch(e) {
      console.log('ocorreu um erro: ' + e);  
    }
}
correto();

Note that this does not solve the error itself, it just corrects the handling of the exception.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.