I'll give you two answers to this problem. The first one requires a slight change your approach. If the Salat DAO functionality is potentially throwing exceptions on insert, you might want to consider changing the createUser
function to return a Try[Option[ObjectId]]
instead and rework it like so:
def createUser (email: String, password: String):Try[Option[ObjectId]] = {
val newUser = User(email = email, password = password)
Try(userDAO.insert(newUser))
}
Now the caller knows that the result will be one of three things: a Success(Some(objectId))
, a Success(None)
(not sure when this will happen but since it's an Option
, you have to be able to handle it) or a Failure
wrapping some exception. This way you could even pattern match on the exception in the Failure
to make sure it's the one thrown on duplicate key and act accordingly as opposed to just swallowing any exception and assuming it must have been due to duplicate key.
Now if you really want a None for any failure, you could just redefine createUser
like this:
def createUser (email: String, password: String):Option[ObjectId] = {
val newUser = User(email = email, password = password)
Try(userDAO.insert(newUser)).toOption.flatten
}
This will swallow any exception from insert
and return a None
.