내가 같이 User
문서를 저장 MongoDB를 수집했습니다 삽입 할 때 데이터베이스 오류를 처리하는 방법 :ReactiveMongo : 새 문서
{
"_id" : ObjectId("52d14842ed0000ed0017cceb"),
"email": "[email protected]",
"firstName": "Joe"
...
}
사용자의 이메일 주소로 고유해야합니다, 그래서에 대한 인덱스를 추가 email
필드 :
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")
}
}
: 여기
collection.indexesManager.ensure(
Index(List("email" -> IndexType.Ascending), unique = true)
)
그리고 내가 새 문서를 삽입하는 방법입니다
오류가 발생하면 위의 코드는 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: { : "[email protected]" }' (code = 11000)]]]
을 ... 그리고 발신자가 더 이상 예외를 처리 할 수 없습니다. 이제 실제 질문은 다음과 같습니다
- 가 어떻게이
recover
섹션에서 다양한 오류 유형 (LastError
에서 제공 즉 사람을) 처리하나요? - 호출자가 예상 예외 (예 :
IllegalArgumentException
)를 받도록하려면 어떻게해야합니까?
문제가 이상하게 보입니다. 고유 한 인덱스를 가진 반응성 문합 (mongo)을 사용합니다. 이미 존재하는 값을 사용하여 문서를 삽입하려고 할 때'insert'를 호출 한 후에 실패한 미래를 얻습니다. 그럼 나는 '회복'이라고 부를 수있다. 나는 미래의 범위를 '벗어나는'예외를 결코 얻지 못했습니다. – vptheron
recover를 사용하여 예외를 throw하지 마십시오. 그 목적은 예외를 잡아서 정확한 결과를 반환하는 것입니다 (귀하의 경우 사용자). 맵 블록에서 try-catch를 사용하고 대신 거기에서 던져주십시오. –
try-catch를 사용해도 결과가 변경되지 않습니다 ... "play.api.Application $$ anon $ 1 : 실행 예외 [[LastError ..." – j3d