Catching scanamo errors within scala

255 Views Asked by At

I'm using scanamo to query a dynamodb table. I want to create a healthcheck method that will return true as long as dynamo can be scanned (i don't care if there are records in the table, i just want to know that the table is there and can be scanned). And i want false to be returned if the table is not present (i fudge the table name as a test). This is the scala code i have right now:

trait DynamoTestTrait extends AbstractDynamoConfig {
  def test(): Future[List[Either[DynamoReadError, T]]] =
    ScanamoAsync.exec(client)(table.consistently.limit(1).scan())
}

and it works when the table is present:

val r = reg.test()
  .map(
    _.headOption.forall(_.isRight)
  )
val e = Await.result(r, scala.concurrent.duration.Duration(5, "seconds"))

but when the table name is incorrect i get an unexpected error:

Unexpected server error: 'Cannot do operations on a non-existent table (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ResourceNotFoundException;

I would have thought that i was trapping that error in my Left. How can i trap this error? does scala have a try/catch construct i could use?

I also tried this but the error still gets thrown and not my catch it seems:

trait DynamoTestTrait extends AbstractDynamoConfig {
  def test(): Future[Boolean] =
    try {
      ScanamoAsync
        .exec(client)(table.consistently.limit(1).scan())
        .map(
          _.headOption.forall(_.isRight)
        )
    } catch {
      case e: ResourceNotFoundException => Future.successful(false)
    }
}

this seems more scalathonic, but always returns true:

trait DynamoTestTrait extends AbstractDynamoConfig {
  def test: Future[Boolean] = {
    val result = Try(ScanamoAsync
      .exec(client)(table.consistently.limit(1).scan())
      .map(
        _.headOption.forall(_.isRight)
      ))
    result match{
      case Success(v) => Future.successful(true)
      case Failure(e) => Future.successful(false)
    }
  }
}
0

There are 0 best solutions below