处理 MongoDB 异常的更好方法
我正在为我的 asp.net 应用程序开发一个 MongoDB 支持的身份验证模块。 MongoDB 数据库有一个用户集合,我在其中存储登录信息 - 用户名、电子邮件和密码。用户名和电子邮件都设置为唯一:
users.ensureIndex({email:1}, {unique:1})
users.ensureIndex({uname:1}, {unique:1})
现在,如果我尝试插入具有现有 uname 或电子邮件的记录,我会收到 MongoDB 异常:
Safemode detected an error: E11000 duplicate key error index:
authdb.users.$email_1 dup key: { : "[email protected]" }
(response: { "err" : "E11000 duplicate key error index: authdb.users.$email_1
dup key: { : \"[email protected]\" }", "code" : 11000, "n" : 0, "connectionId" : 9,
"ok" : 1.0 })
我需要告诉用户他们输入的用户名或电子邮件已经存在,但整个异常只是一团文本,要查看发生了什么,我必须通过查看错误消息文本中是否包含“$email”或“$uname”来猜测。是否有某种 MongoDB 异常解析器可以帮助我检测异常的原因?
I am working on a MongoDB-backed authentication module for my asp.net application. The MongoDB database has a collections of users where I store login information - username, email and password. Both username and email are set to be unique:
users.ensureIndex({email:1}, {unique:1})
users.ensureIndex({uname:1}, {unique:1})
Now, if I try to insert a record with existing uname or email, i get a MongoDB exception:
Safemode detected an error: E11000 duplicate key error index:
authdb.users.$email_1 dup key: { : "[email protected]" }
(response: { "err" : "E11000 duplicate key error index: authdb.users.$email_1
dup key: { : \"[email protected]\" }", "code" : 11000, "n" : 0, "connectionId" : 9,
"ok" : 1.0 })
I need to tell the user that the username or email they entered already exists, but the whole exception is just a blob of text, and to see what's going on I have to guess by looking whether "$email" or "$uname" are in the error message text. Is there some sort of parser for MongoDB exceptions which would help me detect what the exception is for?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我在 MongoDB 的错误跟踪器中创建了一个功能请求,以在重复键错误时向 getLastError 的输出添加额外的字段。请在 https://jira.mongodb.org/browse/SERVER-3069 上投票。
在实现之前,对于您的用例,您只需检查 err 字符串是否包含“email”或“uname”,并从您刚刚尝试插入的文档中检索重复的值。它没有想象中那么优雅,但现在应该可以工作。
I have created a feature request in MongoDB's bug tracker to add extra fields to the output of getLastError on duplicate key errors. Please vote for it at https://jira.mongodb.org/browse/SERVER-3069.
Until that is implemented, for your use case you can just check if the err string contains either "email" or "uname" and retrieve the duplicated value from the document you just tried to insert. It's not as elegant as it could be, but it should work for now.
使用 c# MongoDB 驱动程序 1.xa 可以像这样检测重复项
使用 c# MongoDB 驱动程序 2.x 请参阅 https://stackoverflow.com/a /30309874/516748
但是,如果您想确切地知道哪个重复键,您可能需要解析文本
With c# MongoDB driver 1.x a duplicate can be detected like so
With c# MongoDB driver 2.x see https://stackoverflow.com/a/30309874/516748
But if you want to know exactly which duplicate key you may need to parse the text