nalanart
nalanart

Reputation: 41

Don't get a 404 response for invalid id

I am getting the following error when setting up my workoutId param:

UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "5fb02bd8b61abc02" at path "_id" for model "Workout"

I'm able to successfully make a GET request if the workoutId exists but when I try with an id that doesn't exist, it should give me a 404 response but it doesn't. Is there something that I'm missing?

workoutsRouter.param('workoutId', async (req, res, next, workoutId) => {
  try {
    await mongoose.connect('mongodb+srv://nalanart:[email protected]/workout-app-db?retryWrites=true&w=majority', 
    { useNewUrlParser: true, useUnifiedTopology: true })

    const workout = await Workout.findById(workoutId).exec()

    if(Object.keys(workout).length === 0) {
      res.sendStatus(404)
    } else {
      req.workout = workout
      next()
    }

  } catch(error) {
    throw error
  }
  
})

Upvotes: 0

Views: 65

Answers (1)

J.F.
J.F.

Reputation: 15177

Answering your question is as simple as add res.sendStatus(404) into catch block.

However, is important to know what code return.

404 is for a value not found. So, when the query is done but not return any document, you can send 404. But if the query fails, a better option is send other status code.

In this case 400 code could be a better option. According to mozilla (and many other, this is an standar):

400 Bad Request: The server could not understand the request due to invalid syntax.

Upvotes: 1

Related Questions