Home > Back-end >  Catch error produced by incorrect mongodb New ObjectId() and send error to client
Catch error produced by incorrect mongodb New ObjectId() and send error to client

Time:08-19

I am purposely passing an incomplete id to New ObjectId() while using Mongodb with node.js. As a result, I get the following error:

BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer

I am catching the error in a try/catch. I can console.log the error. However, when I use res.send(error) to receive the error message in the client side(postman), I receive an empty object. I would like to know what would be the proper technique to catch that particular error and send it to the client. This is a simplified version of my code:

try{
const userId = new ObjectId('6w8268bkdkw') //wrong Id
}
catch{
  res.send(error)
}

CodePudding user response:

You are not using try/catch correctly:

try{
const userId = new ObjectId('6w8268bkdkw') //wrong Id
}
catch (error) {
  console.log(error.name); // BSONTypeError
  console.log(error.message); // the message it will send
  console.log(error.stack); // the stack dumps
  res.status(500).send(error);
}

CodePudding user response:

In your route handler function you can code like this, for example:

app.get("/api/:id",  (req, res) => {

    const id = req.params.id

    if (!id || ObjectId.isValid(id) == false) {
        const msg = { message: "The id provided is not valid, "    id };
        res.status(404).send(msg);
        return;
    }

    // code for a valid id goes here...

});
  • Related