在快速HTTP API一致错误验证响应,用猫鼬和穰
我非常新的节点后台开发,因为我是从前端来。我正在开发使用快递,蒙戈,猫鼬和穰输入验证的HTTP API。
我同时使用Mongoose和Joi架构验证,后者只是在特殊情况下,如后/ PUT /补丁路线。
使用在猫鼬架构中的“唯一”规则电子邮件领域,我在下面的问题绊倒:猫鼬的错误响应都相当距离淳佳的人有很大不同。你可以想像,一致的反应应该是首选,以避免对前端复杂的数据分析显示在用户界面中的错误。
这是唯一的电子邮件猫鼬错误响应的一个例子:
{
"errors": {
"email": {
"message": "Error, expected 'email' to be unique. Value: '[email protected]'",
"name": "ValidatorError",
"properties": {
"message": "Error, expected 'email' to be unique. Value: '[email protected]'",
"type": "unique",
"path": "email",
"value": "[email protected]"
},
"kind": "unique",
"path": "email",
"value": "[email protected]"
}
},
"_message": "Author validation failed",
"message": "Author validation failed: email: Error, expected 'email' to be unique. Value: '[email protected]'",
"name": "ValidationError"
}
而这是错误的密码错误穰响应的例子:
{
"isJoi": true,
"name": "ValidationError",
"details": [
{
"message": "\"password\" with value \"3\" fails to match the required pattern: /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,32}$/",
"path": [
"password"
],
"type": "string.regex.base",
"context": {
"pattern": {},
"value": "3",
"key": "password",
"label": "password"
}
}
],
"_object": {
"username": "thequickbrownfox",
"first_name": "The Quick",
"last_name": "Brown Fox",
"email": "[email protected]",
"password": "3"
}
}
请注意,我还使用Mongoose Unique Validator让猫鼬,而不是默认E11000蒙戈错误这是相当无语唯一的错误消息。有没有什么办法让诸如此类的用例类似的错误反应?谢谢。
回答如下:我将通过建立快递中间件错误处理程序捕获从猫鼬和穰不同的错误响应,并将它们转换成适合自己的制服错误响应启动。
例如,在主快递的应用:
app.use(function (err, req, res, next) {
if (err) {
let transformedErrorPayload = parseError(err)
res.status(someErrorCode).json(transformedErrorPayload)
}
})
而你的变换可能是这样的:
parseError(err) {
if ("isJoi" in err && err.isJoi == true) {
// do stuff with the Joi error
return transformedErrorPayload
} else if ("errors" in err && err.errors instanceof Object) {
// do stuff with Mongoose error
return transformedErrorPayload
}
}