Morten Hagh
Morten Hagh

Reputation: 2113

Handle catch in NodeJS DELETE endpoint on findByIdAndDelete

I am trying to find the best to handle a catch error in the output / response.

I have this route that deletes a game by an ID

router.delete("/delete/:id", (req, res) => {
  (async () => {

    try {
      let deleteGame = await gameModel.findByIdAndDelete(ObjectId(req.params.id)).exec();

      if (deleteGame === null) {
        res.json({ error: `No game found with id ${req.params.id}` })
      } else {
        res.json({ message: `Game ${game.name} deleted` })
      }

    } catch (error) {
      console.log(error)
    }

  })();
});

When for example the ID is in an unexpected format mongoose will return Argument passed in must be a single String of 12 bytes or a string of 24 hex characters in the "catch"

I am not sure if it a good practice to do res.json({ message: 'An error occured' }) in the catch - wouldn't that be for the server to log etc.?

Upvotes: 0

Views: 974

Answers (2)

Raj Kumar
Raj Kumar

Reputation: 798

Here is the sample solution for that:

router.delete("/delete/:id", (req, res) => {
  (async () => {

    try {
      let deleteGame = await gameModel.findByIdAndDelete(ObjectId(req.params.id)).exec();

      if (deleteGame === null) {
        res.status(404).send({ error: `No game found with id ${req.params.id}` })
      } else {
        res.status(204).send({ message: `Game ${game.name} deleted`, })
      }

    } catch (error) {
      console.log(error);
      // pass this to error handler middleware, this will give 500
      next(error);
    }

  })();
});

Error handler middleware in server.js or index.js

app.use(function (err, req, res, next) {
res.status(err.status || 500);
    res.json({
        errors: {
            message: err.message || 'Internal Server Error!',
        },
    });
})

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1075309

I am not sure if it a good practice to do res.json({ message: 'An error occured' }) in the catch - wouldn't that be for the server to log etc.?

Well, you need to send some response to the request, regardless of whether you log an error on the server. So yes, it makes sense to call res.json from within the catch. The exact error you return is up to you. (Based on what you do when deleteGame is null, you probably want error rather than message, though.)

Upvotes: 1

Related Questions