我有一个 MongoDB 集合,我在其中存储User
这样的文档:
{
"_id" : ObjectId("52d14842ed0000ed0017cceb"),
"email": "joe@gmail.com",
"firstName": "Joe"
...
}
用户必须是唯一的电子邮件地址,所以我为该email
字段添加了一个索引:
collection.indexesManager.ensure(
Index(List("email" -> IndexType.Ascending), unique = true)
)
这是我插入新文档的方式:
def insert(user: User): Future[User] = {
val json = user.asJson.transform(generateId andThen copyKey(publicIdPath, privateIdPath) andThen publicIdPath.json.prune).get
collection.insert(json).map { lastError =>
User(json.transform(copyKey(privateIdPath, publicIdPath) andThen privateIdPath.json.prune).get).get
}.recover {
throw new IllegalArgumentException(s"an user with email ${user.email} already exists")
}
}
如果发生错误,上面的代码会抛出一个IllegalArgumentException
并且调用者能够相应地处理它。但是如果我recover
像这样修改部分......
def insert(user: User): Future[User] = {
val json = user.asJson.transform(generateId andThen copyKey(publicIdPath, privateIdPath) andThen publicIdPath.json.prune).get
collection.insert(json).map { lastError =>
User(json.transform(copyKey(privateIdPath, publicIdPath) andThen privateIdPath.json.prune).get).get
}.recover {
case e: Throwable => throw new IllegalArgumentException(s"an user with email ${user.email} already exists")
}
}
...我不再得到一个IllegalArgumentException
,但我得到了这样的东西:
play.api.Application$$anon$1: Execution exception[[IllegalArgumentException: DatabaseException['E11000 duplicate key error index: gokillo.users.$email_1 dup key: { : "giuseppe.greco@agamura.com" }' (code = 11000)]]]
...并且调用者不再能够按应有的方式处理异常。现在真正的问题是:
- 如何处理该部分中的各种错误类型(即由 提供的错误类型
LastError
)recover
? - 如何确保调用者获得预期的异常(例如
IllegalArgumentException
)?