有没有更好的方法来过滤未来

Is there better way to filter the Future

所以我想在play-framework中写一个简单的登录逻辑。密码检查看起来像这样

...
.filter(user => BCrypt.checkpw(req.password, user.password))
...

一切正常。但是当密码不正确时,我得到异常:

Future.filter predicate is not satisfied

但是,我想抛出自己的异常,所以我这样做了:

...
 .map(user =>
        if (!BCrypt.checkpw(req.password, user.password)) {
          throw WrongCredentials()}
        else user)
...

哪个可行,但我一直想知道是否有更简洁的方法。

你可以这样做(来自官方文档):

val purchase: Future[Int] = rateQuote map {
  quote => connection.buy(amount, quote)
} recover {
  case QuoteChangedException() => 0
}