What does an example MongoDB error look like on the NodeJS native driver?

10.5k views Asked by At

I can't seem to find any examples of MongoDB error objects in their documentation or on the internet.

What does an example MongoDB error object look like? I'd like to "handle" the error and/or reformat it for my own purposes, depending on what the error is.

2

There are 2 answers

0
JohnnyHK On BEST ANSWER

As of MongoDB 2.4.8 with the mongodb 1.3.23 driver, they look like this:

{
  "name":"MongoError",
  "err":"E11000 duplicate key error index: test.test.$country_1  dup key: { : \"XYZ\" }",
  "code":11000,
  "n":0,
  "connectionId":10706,
  "ok":1
}
1
lifeisfoo On

MongoError objects

With newer versions of the node-mongodb-driver (>= 2) things are a little bit different.

Inside the nodejs driver source code 2.2 you can see that the error object properties can be various (see line 34). Only name and message fields are always available.

This is an interesting piece of code from mongodb-core/lib/error.js (v2.2), look at the last for loop.

function MongoError(message) {
  this.name = 'MongoError';
  this.message = message;
  Error.captureStackTrace(this, MongoError);
}

MongoError.create = function(options) {
  var err = null;
  if(options instanceof Error) {
    err = new MongoError(options.message);
    err.stack = options.stack;
  } else if(typeof options == 'string') {
    err = new MongoError(options);
  } else {
    err = new MongoError(options.message || options.errmsg || options.$err || "n/a");
    // Other options
    for(var name in options) {
      err[name] = options[name];
    }
  }
  return err;
}

So, an error object will looks, at least, like this:

{
   "name": : "MongoError",
   "message": "E11000 duplicate key error collection: main_db.stores index..."
}

err.code field

So, there is no guarantee for other fields, but code is pretty common (and very useful). This number is a mongodb internal error code and the driver just add it to the MongoError object when available. You can find the latest error codes list inside a mongodb source code file: error_codes.yml.

An interesting example about how the nodejs driver manage mongodb error codes, is the collection bulkWrite source code, that uses the toError utils with a code to throw a MongoError.

node-mongodb-driver 3.x

The MongoError source code has been refactored but the error model is essentially the same.