https://kotlinlang.org logo
#arrow
Title
# arrow
m

Michael Friend

02/28/2023, 9:06 PM
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

simon.vergauwen

02/28/2023, 9:31 PM
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

Michael Friend

03/01/2023, 12:25 AM
nice i like that DSL inside either. Thanks!
4 Views