0

I'm writing a registration form in my application, the user's name and the user's email must be unique. I run a mysql database and use node-mysql (v 2.0.0) as driver.

When a user tries to use a name that is allready registered in the database, mysql raises the following error : Error: ER_DUP_ENTRY: Duplicate entry 'John' for key 'nickname', but in the Error object raised by node-mysql contains no usefull informations about the error :

console.log(JSON.stringify(err));

{"code": "ER_DUP_ENTRY", "errno": 1062, "sqlState": "23000", "index": 0}

Where can I get the involved entry and key ? I need to know which of the key nickname or the key email is responsible for the duplicate key error, so that I can warn the user.

I know I can find this info doing err.toString() and parsing the result (which contains is the mysql error string itself) but I would like to know if there is a better way to do so.

1 Answers1

1

The reason you don't see the message and other Error properties is that some of those "standard" properties are not set as enumerable and as a result JSON.stringify() does not pick them up.

You could add a toJSON() to Error that correctly returns serializes all properties. This method is automatically called by JSON.stringify() if it detects its existence on the value you pass in. Example:

var config = {
  configurable: true,
  value: function() {
    var alt = {};
    var storeKey = function(key) {
      alt[key] = this[key];
    };
    Object.getOwnPropertyNames(this).forEach(storeKey, this);
    return alt;
  }
};
Object.defineProperty(Error.prototype, 'toJSON', config);
mscdex
  • 104,356
  • 15
  • 192
  • 153