O
O
Oleksandr Tatarinov2018-05-27 19:10:47
JavaScript
Oleksandr Tatarinov, 2018-05-27 19:10:47

How to check for error type in node js+express?

How can I check for the type of error? So that if the file is not found, then 404, and if something else, then 500. Now I did this, but it constantly gives out that it was not found, even if there is actually a product.

router.get('/:productId',(req,res,next) => {
  const id = req.params.productId
  ObjectId = mongoose.Types.ObjectId
  if (!ObjectId.isValid(id)) {
    res.status(404).json({
      message: 'Invalid id!'
    })
  } else {
    Product.findById(id)
    .exec(doc => {
      if ( doc ) {
        console.log(doc)
        res.status(200).json(doc)
      } else {
        res.status(404).json({
          message: 'Not found!'
        })
      }
    })
  }
  })

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question