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.