diff --git a/lib/validations.js b/lib/validations.js index 200bf6ba..a12a8127 100644 --- a/lib/validations.js +++ b/lib/validations.js @@ -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); +} diff --git a/package.json b/package.json index 09efe955..fb56d97e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "loopback-datasource-juggler", - "version": "1.5.1", + "version": "1.5.2", "description": "LoopBack DataSoure Juggler", "keywords": [ "StrongLoop", diff --git a/test/validations.test.js b/test/validations.test.js index f01414aa..c3b5c8d4 100644 --- a/test/validations.test.js +++ b/test/validations.test.js @@ -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(); + }); + }); }); });