mac- / ratify

A Hapi plugin for validating the schema of path, query, request body, and response body params using JSON-schema
MIT License
71 stars 27 forks source link

Include field information in errors #12

Closed dschenkelman closed 10 years ago

dschenkelman commented 10 years ago

Issue

Error messages on failed types do not include property name.

Example

Currently, the following validation:

ratify: {
  payload: {
    type: "object",
    properties: {
      outer: {
        type: "object",
        properties: {
          inner:{
            type: "string"
          }
        }
      }
    }
  }
}

Together with this payload:

{
  "outer": {
    "inner": false
  }
}

Results in this response:

{
    "statusCode": 400,
    "error": "Bad Request",
    "message": "payload parameters validation error: invalid type: boolean (expected string)"
}

Proposal

The available information when creating the error message is:

{ code: 'INVALID_TYPE',
  message: 'invalid type: boolean (expected string)',
  path: '#/outer/inner',
  params: { expected: 'string', type: 'boolean' } }

The current code looks like this:

if (!report.valid) {
  errorMessages = 'payload parameters validation error: ' +
          _.map(report.errors, function(error) { console.log(error); return error.message; }).join(', ');
  return next(plugin.hapi.error.badRequest(errorMessages));
}

If it were updated to something like this it would provide more detailed error messages:

if (!report.valid) {
  errorMessages = 'payload parameters validation error: ' +
      _.map(report.errors, function(error) { 
        var message = error.message;
        message += ' - on ';
        // handle array case
        message += error.path.substr(2).replace(/\//g, ".").replace(/\.\[/g, "[")
        return message;
      }).join(', ');
dschenkelman commented 10 years ago

BTW, I will implement it if you give me the :+1:

mac- commented 10 years ago

Yeah, go for it! Thanks