从Node.js返回Mongoose的错误

时间:2018-02-10 11:37:36

标签: node.js mongodb mongoose

我以下列格式从Mongoose收到错误

{
    "errors": {
        "companyName": {
            "message": "Error, expected `companyName` to be unique. Value: `priStore`",
            "name": "ValidatorError",
            "properties": {
                "type": "unique",
                "message": "Error, expected `{PATH}` to be unique. Value: `{VALUE}`",
                "path": "companyName",
                "value": "priStore"
            },
            "kind": "unique",
            "path": "companyName",
            "value": "priStore",
            "$isValidatorError": true
        },
        "companyEmail": {
            "message": "Error, expected `companyEmail` to be unique. Value: `pri@gmail.com`",
            "name": "ValidatorError",
            "properties": {
                "type": "unique",
                "message": "Error, expected `{PATH}` to be unique. Value: `{VALUE}`",
                "path": "companyEmail",
                "value": "pri@gmail.com"
            },
            "kind": "unique",
            "path": "companyEmail",
            "value": "pri@gmail.com",
            "$isValidatorError": true
        }
    },
    "_message": "Client validation failed",
    "message": "Client validation failed: companyName: Error, expected `companyName` to be unique. Value: `priStore`, companyEmail: Error, expected `companyEmail` to be unique. Value: `pri@gmail.com`",
    "name": "ValidationError"
}

我需要以良好的格式在客户端展示,如

错误

  1. 公司名称已存在
  2. 公司电子邮件已存在
  3. 我应该在客户端或Node.js端解析错误吗?在Node.js端,我可以返回客户端可以显示给用户的相应错误消息吗?

1 个答案:

答案 0 :(得分:0)

您可以通过创建一个辅助方法将错误对象转换为Node.js中的消息数组,该方法接受Mongoose错误对象,遍历errors属性并根据预定义的错误字典将错误消息推送到数组类型及其消息。

以下函数描述了上述转换和示例用法:

const handleError = err => {
    const dict = {
        'unique': "% already exists.",
        'required': "%s is required.",
        'min': "%s below minimum.",
        'max': "%s above maximum.",
        'enum': "%s is not an allowed value."
    }

    return Object.keys(err.errors).map(key => {
        const props = err.errors[key].properties
        return dict.hasOwnProperty(props.kind) ?
            require('util').format(dict[props.kind], props.path) :
                props.hasOwnProperty('message') ? 
                    props.message : props.type
    })
}

使用示例:

company.save(err => {
    if (err) res.send({ errors: handleError(err) })
}