sails-mongo adapter, normalize error messages

时间秒杀一切 提交于 2019-12-10 20:49:24

问题


I am trying out sailsJs with mongodb using the sails-mongo adapter. After adding validations to a model, I get the following response when the validation fails.

Users.js Model:

module.exports = {
    schema: true,
    attributes: {
        name: {
            type: "string",
            unique: true
        },
        email: {
            type: "email",
            unique: true
        },
        password: {
            type: "string",
            required: true
        }
    }
}   

Validation error while using sails-mongo adapter:

{
  "error": {
    "error": "E_UNKNOWN",
    "status": 500,
    "summary": "Encountered an unexpected error",
    "raw": {
      "name": "MongoError",
      "code": 11000,
      "err": "E11000 duplicate key error index: eReporterDB.users.$name_1 dup key: { : \"codin\" }"
    }
  }
}

I get a better formatted response if I use the in development database which is the sails-disk adapter.

Validation error while using sails-disk adapter:

{
  "error": {
    "error": "E_VALIDATION",
    "status": 400,
    "summary": "2 attributes are invalid",
    "invalidAttributes": {
      "name": [
        {
          "value": "codin",
          "rule": "unique",
          "message": "A record with that `name` already exists (`codin`)."
        }
      ]
    }
  }
}

As a developer, I would expect a standardized response from a framework, Can anyone help me with a graceful way of handling such validation errors. I mean I cannot just show the error "E11000 duplicate key error index: eReporterDB.users.$name_1 dup key: { : \"codin\" }" to a layman user.

Thanks.


回答1:


sails.js is just reporting the error given by the database. It's just the case that sails-disk has nicer error messages. The sails-mongo adapter ends up giving you the error that's reported directly by the database; so to prettify these, you'd just need to map the raw errors into more user-friendly messages just like any other database driver.



来源:https://stackoverflow.com/questions/29443791/sails-mongo-adapter-normalize-error-messages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!