Rafael Spessotto
Rafael Spessotto

Reputation: 171

NodeJS Error Handling - Throwing error promise to try catch

im trying to get the promise error, and throw to the "try catch" to concentrate the return of the error in one place.

like this:

async schedule(req, res) {
        try {

            //here is the function that returns a promise
            service.search()
                .then(async data => {

                    if (data.length > 0) {   
                            res.status(200).json("OK!");                        
                    }
                })
                .catch(async error => {
                   //here i want to throw this error to the "try catch" to return the error message
                   throw new Error(error);                  
                })

        }
        catch (error) {
            res.status(400).json(error);
        };

    }

but when goes to "throw new Error(error);" gives me the message:

(node:15720) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
    warning.js:27

someone could help me to understand what im doing wrong?

thank so much!

Rafael

UPDATE

based on the Marcos answer, i did:

async schedule(req, res) {
        try {

            const data = await service.search();                      

            if (data.length > 0) {   
                res.status(200).json("OK!");                        
            }               

        }
        catch (error) {
            res.status(400).json(error);
        };

  } 

and worked... Now i understand how to handle this errors... thanks!

Upvotes: 0

Views: 42

Answers (1)

Marcos Casagrande
Marcos Casagrande

Reputation: 40444

You either use async/await with a try/catch or .then/.catch, you don't mix both ways.

async schedule(req, res) {
    try {

        //here is the function that returns a promise
        // If service.search rejects, it will go to the `catch`
        const data = await service.search()


        if (data.length > 0) {   
            return res.status(200).json("OK!");                        
        }
        // do something here
        // res.status(400).send('Invalid data')
        // throw new Error('Invalid data')

    } catch (error) {
        res.status(400).json(error);
    }

}

or

schedule(req, res) {
   service.search()
      .then(data => {

          if (data.length > 0) {   
                  res.status(200).json("OK!");                        
          }
      })
      .catch(error => {
          res.status(400).json(error);                 
      })
}

Upvotes: 1

Related Questions