1

In my user model I have something like this:

register: function(data, next) {
    User.findOne({email:data.email}).exec(function findOneUserCB(err, user) {
        if (!err && user) {
            return next(new Error('Email already exist.'));
        }
        // other things
    });
}

I'm basically trying to return a custom error when the user is found but there isn't any other error from waterline. But this doesn't work, sails complains that TypeError: Cannot call method 'toString' of undefined.

So I've tried to emulate a waterline error:

//...
var error = {
    code: 'E_UNIQUE',
    details: 'Invalid',
    model: 'user',
    invalidAttributes: {
        hase: []
    },
    status: 400
}
return next(error);
//...

This works but it feels very hackish. Isn't it a better way to pass a custom error from within a query callback? I couldn't find any documentation about this topic

Leonardo
  • 4,046
  • 5
  • 44
  • 85

1 Answers1

0

You can try something like this

register: function(data, next) {
    User.findOne({email:data.email}).exec(function findOneUserCB(err, user) {
    if(user){
      var alreadyExists = new Error();
      alreadyExists.message = require('util').format('User already exists');
      alreadyExists.status = 400;
      cb(alreadyExists);
    }
    // other things
});
clemens
  • 16,716
  • 11
  • 50
  • 65