[Fixed] Catch block is not working as intended while trying to delete with an invalid ObjectId

Issue

The try block is working fine and I get the response as intended.
However, when I try to delete with an invalid Object ID, the catch block does not work as intended. I should be getting a json response in Postman but I get nothing.

Here’s the route handler:

blogRouter.delete('/:id', async (request, response) => {
        const blogId = await Blog.findById(request.params.id)
      try {
          if(blogId) {
            await Blog.findByIdAndRemove(blogId)
            response.status(204).end()
          } else {
              response.status(404).end()
          }
      } catch(error) {
          response.status(400).json({error: error.message})
      }

This is what I get in the console:

(node:5820) UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "60618f98b376810cb85acffba" at path "_id" for model "Blog"
    at model.Query.exec (E:\fullstackopen part4\bloglist\node_modules\mongoose\lib\query.js:4361:21)
    at model.Query.Query.then (E:\fullstackopen part4\bloglist\node_modules\mongoose\lib\query.js:4455:15)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:5820) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:5820) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Method: DELETE
Path: /api/blogs/60618f98b376810cb85acffba
Request Body: {}
----
(node:5820) UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "60618f98b376810cb85acffba" at path "_id" for model "Blog"
    at model.Query.exec (E:\fullstackopen part4\bloglist\node_modules\mongoose\lib\query.js:4361:21)
    at model.Query.Query.then (E:\fullstackopen part4\bloglist\node_modules\mongoose\lib\query.js:4455:15)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
(node:5820) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)

What could be wrong here? My guess is that It has something to do with async/await because the console is giving UnhandledPromiseRejectionWarning.

Solution

You also need to put the first promise into try catch

blogRouter.delete('/:id', async (request, response) => {
  // const blogId = await Blog.findById(request.params.id) // FROM HERE
  try {
      const blogId = await Blog.findById(request.params.id) // TO HERE
      if(blogId) {
        await Blog.findByIdAndRemove(blogId)
        response.status(204).end()
      } else {
          response.status(404).end()
      }
  } catch(error) {
      response.status(400).json({error: error.message})
  }

Leave a Reply

(*) Required, Your email will not be published