本文介绍了sails-mongo适配器,规范化错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用sails-mongo适配器在mongodb中尝试sailsJs.将验证添加到模型后,验证失败时会收到以下响应.

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模型:

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

使用sails-mongo适配器时发生验证错误:

{
  "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\" }"
    }
  }
}

如果我使用开发数据库(即sails-disk适配器),则会得到更好的格式化响应.

I get a better formatted response if I use the in development database which is the 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`)."
        }
      ]
    }
  }
}

作为开发人员,我希望框架能够提供标准化的响应,任何人都可以通过一种优雅的方式来帮助我处理此类验证错误.我的意思是我不能只向外行用户显示错误"E11000 duplicate key error index: eReporterDB.users.$name_1 dup key: { : \"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.

谢谢.

推荐答案

sails.js仅报告数据库给出的错误.只是sails-disk具有更好的错误消息的情况. sails-mongo适配器最终给您错误,该错误由数据库直接报告.因此,为了美化它们,您只需要像其他数据库驱动程序一样,将原始错误映射到更用户友好的消息中即可.

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.

这篇关于sails-mongo适配器,规范化错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 13:45