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

大城市里の小女人 提交于 2020-01-02 04:02:13

问题


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.


回答1:


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
}



回答2:


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.err.

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.



来源:https://stackoverflow.com/questions/20597773/what-does-an-example-mongodb-error-look-like-on-the-nodejs-native-driver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!