Merge pull request #116 from strongloop/feature/improve-validation-error-toString

validations: include more details in `err.message`
This commit is contained in:
Miroslav Bajtoš 2014-05-20 17:46:26 +02:00
commit 8b29ad0974
2 changed files with 44 additions and 3 deletions

View File

@ -687,12 +687,18 @@ function ValidationError(obj) {
if (!(this instanceof ValidationError)) return new ValidationError(obj);
this.name = 'ValidationError';
this.message = 'The Model instance is not valid. ' +
'See `details` property of the error object for more info.';
var context = obj && obj.constructor && obj.constructor.modelName;
this.message = util.format(
'The %s instance is not valid. Details: %s.',
context ? '`' + context + '`' : 'model',
formatErrors(obj.errors) || '(unknown)'
);
this.statusCode = 422;
this.details = {
context: obj && obj.constructor && obj.constructor.modelName,
context: context,
codes: obj.errors && obj.errors.codes,
messages: obj.errors
};
@ -701,3 +707,19 @@ function ValidationError(obj) {
}
util.inherits(ValidationError, Error);
function formatErrors(errors) {
var DELIM = '; ';
errors = errors || {};
return Object.getOwnPropertyNames(errors)
.filter(function(propertyName) {
return Array.isArray(errors[propertyName]);
})
.map(function(propertyName) {
var messages = errors[propertyName];
return messages.map(function(msg) {
return '`' + propertyName + '` ' + msg;
}).join(DELIM);
})
.join(DELIM);
}

View File

@ -111,6 +111,25 @@ describe('validations', function () {
done();
});
it('should include validation messages in err.message', function(done) {
delete User._validations;
User.validatesPresenceOf('name');
User.create(function (e, u) {
should.exist(e);
e.message.should.match(/`name` can't be blank/);
done();
});
});
it('should include model name in err.message', function(done) {
delete User._validations;
User.validatesPresenceOf('name');
User.create(function (e, u) {
should.exist(e);
e.message.should.match(/`User` instance/i);
done();
});
});
});
});