Errorhandling in node.js

Problem

I want to create a mongoID using an URI fragment as source. However, unless the URI really contains a properly formatted mongoId, I get the below error thrown.

What should I change to allow _id creation without throwing errors as wrapping it in a try/catch block doesn't do it?

Error:

500 Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters in hex format

The code:

var _id = db.bson_serializer.ObjectID.createFromHexString(req.params.id);

this.db.users.findById(_id, function(err, doc) {
    if (!err && !!doc) { res.send(JSON.stringify(doc)); } else {res.send(JSON.stringify({error: "Not found"));}
});

I use the mongoskin driver.

Problem courtesy of: Industrial

Solution

The error is being thrown on this line:

var _id = db.bson_serializer.ObjectID.createFromHexString(req.params.id);

If you wrap that in try/catch block it should work.

var _id = null
try {
  _id = db.bson_serializer.ObjectID.createFromHexString(req.params.id);
} catch (err) {
  res.send(JSON.stringify({error: "Not found"}));
  return;
}

this.db.users.findById(_id, function(err, doc) {
  if (!err) { 
    res.send(JSON.stringify(doc)); 
  } else {
    res.send(JSON.stringify({error: err.message}));
  }
});

Does this work for you?

Solution courtesy of: JP Richardson

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.