简体   繁体   中英

error from slick in play scala

I play around with scala, play and slick. I am wondering how I would catch an error from slick in play.

Lets say, there is an DAO:

trait UserDao extends DAOSlick with UserComponent with HasDatabaseConfig[JdbcProfile] {
  import driver.api._

  def getUserWithId(id: UUID) = {
    db.run(userTable.filter { x => x.userId === id }.result.head)
  }
}

This trait is used in my Controller:

class UserController extends Controller with UserDao {
  import driver.api._

   def getUser(id: String) = Action.async { implicit request =>
    getUserWithId(UUID.fromString(id)).map {
      res => Ok(Json.toJson(res))
    }
  }
}

If there is no user with given ID, slick will raise an error:

[NoSuchElementException: Invoker.first]

In my client (browser), I get an Status 500 (Internal Server Error). I don't find examples, how slick and play is supposed to work together with error messages from the database or slick.

Should the return type of all DAOs be an Try[User]? In all examples I saw, nobody cares about failing slick calls. What am I missing?

Should the return type of all DAOs be an Try[User]? In all examples I saw, nobody cares about failing slick calls. What am I missing?

You are missing Option . Change your DAO method to return Option[User] and instead calling head call headOption on result .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM