Currently, I am working on setting up CRUD routes using Express and Knex. When it comes to the update and delete routes, I have encountered an issue regarding handling cases where the provided ID does not exist in the database. In such situations, I need to display an error message along with a status code of 400. I suspect that there might be an issue in my code preventing it from reaching the catch block to handle this error scenario. Could it be necessary to implement a condition to check for IDs that are not present in the database?
I attempted to address this by adding an if statement to check if the length of the ID is equal to 0, but unfortunately, when testing with Postman using an ID that is not in the database, I was still receiving a status code of 200 instead of 400. Here is the snippet of code I am currently working with in my Express routes:
//PUT update todo
router.put('/:id', (req, res) => {
knex('todos')
.where({
id: req.params.id
})
.update(req.body)
.returning('*')
.then(todos => {
res.status(201).json(todos[0])
})
.catch(error => {
res.status(400).send(error)
});
})
//DELETE
router.delete('/:id', (req, res) => {
knex('todos')
.where({
id: req.params.id
})
.del()
.then(function() {
knex.select() //select all *
.from('todos')
.then(function(todos){
res.status(200)
res.send(todos);
})
})
.catch(error => {
// console.log(error.message)
res.status(400).send(error.message)
})
})