Mohamed Sobhy
Mohamed Sobhy

Reputation: 171

nodejs keeps loading when Unhandled Promise Rejection Error

I'm new to nodeJS I'm trying to select one single board based on request Params

router.get('/board/:id', gettingSingleBoard); 

and this is the getting single board function

gettingSingleBoard = async function (req, res) {
  const id = req.params.id;
  const board = await Board.findOne({ _id: id });
  res.json(board);
};

when I search with valid ID it works well , but when I try to enter ID that is not exits console logs "UnhandledPromiseRejectionWarning: Unhandled promise rejection" and it keeps loading and not returning with error or something

Upvotes: 0

Views: 92

Answers (2)

Jonas Wilms
Jonas Wilms

Reputation: 138267

Another possibility would be catching the error to an error object:

res.json(
  await Board
          .findOne({ _id: id })
          .catch(e=>({error:500,message:e}))
);

Upvotes: 0

Vitaliy Mazurenko
Vitaliy Mazurenko

Reputation: 146

You need to wrap your async code with try/catch. See the example:

gettingSingleBoard = async function (req, res) {
  const id = req.params.id;
  try {
      const board = await Board.findOne({ _id: id });
      res.json(board); 
  } catch(e) {
      res.status(404).send({type: "NotFoundException"})
  }
};

Upvotes: 4

Related Questions