我正在处理node.js服务器应用程序中的请求错误处理。我已经定义了一个处理这些错误的回调函数:
app.use(function errorHandler(err, req, res, next) {
res.send(err, {status: err, message: 'error'});
}
);
这对我作为开发人员来说很好,因为它会打印出这样的堆栈跟踪:
{
"status": {
"stack": "Error\\\n at MongooseError.ValidationError (/home/osboxes/skipodium_rest_server/node_modules/mongoose/lib/error/validation.js:22:16)\\\n at model.Document.invalidate (/home/osboxes/skipodium_rest_server/node_modules/mongoose/lib/document.js:1216:32)\\\n at /home/osboxes/skipodium_rest_server/node_modules/mongoose/lib/document.js:1090:18\\\n at validate (/home/osboxes/skipodium_rest_server/node_modules/mongoose/lib/schematype.js:653:7)\\\n at /home/osboxes/skipodium_rest_server/node_modules/mongoose/lib/schematype.js:681:9\\\n at Array.forEach (native)\\\n at SchemaString.SchemaType.doValidate (/home/osboxes/skipodium_rest_server/node_modules/mongoose/lib/schematype.js:658:19)\\\n at /home/osboxes/skipodium_rest_server/node_modules/mongoose/lib/document.js:1088:11\\\n at process._tickCallback (node.js:415:13)",
"message": "User validation failed",
"name": "ValidationError",
"errors": {
"email": {
"properties": {
"regexp": {},
"type": "regexp",
"message": "Path `{PATH}` is invalid ({VALUE}).",
"path": "email",
"value": "test@exa@mple.com"
},
"stack": "Error\\\n at MongooseError.ValidatorError (/home/osboxes/skipodium_rest_server/node_modules/mongoose/lib/error/validator.js:25:16)\\\n at validate (/home/osboxes/skipodium_rest_server/node_modules/mongoose/lib/schematype.js:652:13)\\\n at /home/osboxes/skipodium_rest_server/node_modules/mongoose/lib/schematype.js:681:9\\\n at Array.forEach (native)\\\n at SchemaString.SchemaType.doValidate (/home/osboxes/skipodium_rest_server/node_modules/mongoose/lib/schematype.js:658:19)\\\n at /home/osboxes/skipodium_rest_server/node_modules/mongoose/lib/document.js:1088:11\\\n at process._tickCallback (node.js:415:13)",
"message": "Path `email` is invalid (test@exa@mple.com).",
"name": "ValidatorError",
"kind": "regexp",
"path": "email",
"value": "test@exa@mple.com"
}
}
},
"message": "error"
}
但是,我希望以生动,用户友好的格式显示生产版本,而不会泄漏整个堆栈跟踪。现在我可以在每个请求处理函数中指定错误状态和消息,但是仍然存在特定信息,如上所述,输入的电子邮件无效,并且我不想手动为每个字段键入它由验证员检查。是否有任何现有的样板供我使用?
答案 0 :(得分:1)
Mongoose验证错误是一个难以处理的问题。我的一般方法是只采取第一个错误(让用户一次处理一个错误)并发送路径和消息,因为其余部分确实为非开发人员提供了更多额外的意义。
first = err.errors[Object.keys(err.errors)[0]]
res.send({
path: first.path,
message: first.message
});
我还建议您使用自定义API样式的错误格式,以便对所有错误采用这种格式 - 这样可以使维护更加轻松。
我有一套我依赖的预定义错误模板 - 这里是一个。
// If the client missed a required parameter
exports.missingParam = function (res, domain, param) {
res.status(400).send({
status: "failed",
errors: [
{
status: "400",
domain: domain,
reason: "required",
message: "Required parameter: "+param,
locationType: "parameter",
location: param
}
]
});
}