Skip to content

Instantly share code, notes, and snippets.

@mikermcneil
Created January 11, 2014 02:09
Show Gist options
  • Save mikermcneil/8366092 to your computer and use it in GitHub Desktop.
Save mikermcneil/8366092 to your computer and use it in GitHub Desktop.
hack to determine whether an error is a validation error from waterline (for Sails/Waterline 0.9.x)
var _ = require('lodash');
/**
* `isValidationError`
*
* Is this a waterline validation error?
*/
function isWaterlineValidationError (err) {
if (_.isPlainObject(err)) {
var keys = Object.keys(err);
if (keys.length) {
var failedValidation = err[keys[0]];
if (_.isArray(failedValidation) && failedValidation.length &&
_.isPlainObject(failedValidation[0]) && failedValidation[0]['rule']
) {
return true;
}
}
}
if ( _.isString(err) && err.match(/duplicate key value violates unique constraint/g) ) {
return true;
}
if ( _.isString(err) && err.match(/^Bad request/ig)) {
return true;
}
return false;
}
@mikermcneil
Copy link
Author

@danegigi @basco-johnkevin @afonsomota Hey y'all- check out the latest version of Sails/Waterline on master branch on github. Waterline errors have been normalized into a more predictable format. Still needs some work/testing, but the situation is much better now.

@dezull
Copy link

dezull commented Nov 26, 2014

@mikermcneil Is okay to just check e.code ? as on master

  if (e.code && e.code === 'E_VALIDATION') {
    // var validationErrors = e.invalidAttributes;
  }

@lykmapipo
Copy link

For sails v0.11.X you may use this sails-hook-validation

@mrTimofey
Copy link

More compact solution

function(err, model) {
    // no errors
    if (!err) return true;
    // error is not a validation error
    if (!err.ValidationError) return false;
    // { field: { rule: 'Message', otherRule: 'Message' ... } ... }
    var messages = model.validationMessages,
        errors = err.ValidationError,
        output = {};

    Object.keys(errors).forEach(function(field) {
        output[field] = [];
        errors[field].forEach(function(error) {
            output[field].push(messages[field] && messages[field][error.rule] || error.rule);
        })
    });

    return output;
}

@mikermcneil
Copy link
Author

Note that in Sails v1 this is changing a bit. For details, see the docs on sailsjs.com (or balderdashy/sails#3459 (comment) for a bit more background)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment