0
votes

What would be the best way to execute a DB operation and return a response in the controller depending on the result of the operation?

Example there is a DAO, call it AccountDAO which has a method

def insert(account: Account): Future[Account]

In my Service layer, AccountService I will do,

def create(account: Account) : Try[Future[Account]] = Try {
  accountDAO.insert(account)
}

Then in my controller

accountService.create(account) match {
   case Success(account) => // This will return a Future[Account]
                            // returns a created response
   case Failure(e) => // returns a 500 response
}

What is the better way to do this?

1

1 Answers

0
votes

You can also use recover in the Future. Here's example:

def create(account: Account) : Future[Account] = accountDAO.insert(account)

and in controller:

accountService.create(account).map{
   OK(Json.toJson(_)) //returns a response
}.recover {
    case ex => // returns a 500 response
}

I guess here's no "best" solution.