Is there a recommended way to handle exceptions wi...
# arrow
m
Is there a recommended way to handle exceptions within an
either {}
comprehensions and map those exceptions to a Left value? Right now i have something like this where i just catch the exception with Either.catch and map it to the right left type
Copy code
suspend fun foo(): Either<String, List<Data>> = either { 
   val data = api.getData().bind()
   return@either Either.catch { doFileStuff }.mapLeft { it.message }
}
s
Either.catch
and
mapLeft
is the most common way of doing that and is considered idiomatic usage. In
1.1.6-alpha.28
, will be released next month as
1.2.0
, we've added
catch
as a DSL. That'll allow you to do:
Copy code
either {
  val res = catch({ doFileStuff() }) { ex: Throwable ->
    raise(it.message)
    // fallback value
  }
    val res2 = catch({ doFileStuff() }) { ex: FileNotFountException ->
    raise("file-not-found")
    // fallback value
  }
}
m
nice i like that DSL inside either. Thanks!