I have this method:
def findById(id: String): Customer = {
(new CustomerDaoEs).retrieve(Id[Customer](id)) onComplete {
case Success(customer) => customer
case Failure(t) => {
throw new InvalidIdException(id.toString, "customer")
}
}
}
Of course, the issue is that this returns Unit instead of Customer... So basically onComplete does not really behave like pattern matching.
Is there any way to keep returning Customer (or Option[Customer]) and make this work nice (I mean to keep this onComplete clean structure)?
You could change exception using recover method:
def findById(id: String): Future[Customer] = {
(new CustomerDaoEs).retrieve(Id[Customer](id)).recover{ case _ => throw new InvalidIdException(id.toString, "customer") }
}
Then you could use your method like this:
val customer = Await.result(findById("cust_id"), 5.seconds)
Alternatively you could replace exception with None:
def findById(id: String): Future[Option[Customer]] = {
(new CustomerDaoEs).
retrieve(Id[Customer](id)).
map{ Some(_) }.
recover{ case _ => None }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With