torayeff
torayeff

Reputation: 9702

Sails.js handling attribute validation errors

In Sails.js it is possible to use different database connections for models and it is easy to change database (MySQL or MongoDB). The problem arises when I want to display validation errors. These are my codes:

Groups.js model

...
    connection: 'MysqlConnection', //or connection: 'MongodbConnection'
    attributes: {
        id: {
            type: 'string',
            unique: true
        },
        name: {
            type: 'string',
            required: true
        },
...

GroupsController.js controller:

...
//add group to database
Groups.create(group, function (err, data) {
    if (err) {
        console.log(err);
        res.send('Error'); // is it possible to send only validation error
        return;
    } else {
        res.send(data);
    }
});
...

Should I handle each attribute validation error separately, is it possible to send only validation error?

MySQL returns:

Error (E_VALIDATION) :: 1 attribute is invalid ...

MongoDB returns:

Error (E_UNKNOWN) :: Encountered an unexpected error ...

Upvotes: 1

Views: 673

Answers (1)

Maxtermax
Maxtermax

Reputation: 145

you can try:

      Model.catch(function(err) {
        var inspect = Object.keys(err)// [ "reason","invalidAttributes", ".."        ]
        console.log(  Object.keys(err.invalidAttributes) ) // ["name","etc.."]
      })

to catch the error

Upvotes: 1

Related Questions