Using try...catch to handle errors properly in express backend

Viewed 18

I've been using Express for a while to make a backend API. I recently realized I vastly underestimated the amount of error handling I needed to be doing and I wanted to make sure I was doing it correctly before fixing my API.

Here is an example:

router.post('/example', function(req,res,next){
  //try...catch is not needed here because express automatically places routes in a try...catch

  QueryDatabase('SELECT * FROM accounts WHERE uuid = ?', req.session.uuid, (err, result) => {
    //Assuming QueryDatabase uses asychronous callback there needs to be another try...catch in the callback
    if (err) return next(err);
    try {
      let email = result[0].email;

      //Assuming HideEmail uses sychronous callback there does not need to be another try...catch because the outer try catch will catch errors
      HideEmail(email, (err, result) => {
        if (err) return next (err);

        let hiddenEmail = result;

        //Assuming GetVerified uses asychronous callback there still does not need to be try catch because no error could be thrown. 
        //(although maybe one should still be added im not too sure)
        GetVerified(email, (err, result) => {
          if (err) return next (err);

          res.send({email:hiddenEmail, verified:result});
        })
      })
    } catch (error) {
      next(error);
    }
  })
})

Is it a good idea to do this and keep all my code contained in a try...catch of some kind and when an asynchronous callback is used to make another try...catch as well? I feel like this is the safest option so that the API will never crash due to an unhandled error, but I am rather new and don't know too much of what I'm doing.

0 Answers
Related