Is there a built-in variant of Either/Validated `c...
# arrow
s
Is there a built-in variant of Either/Validated
catch
that only handles specific exceptions and throws the rest?
t
I have a function for your usecase:
Copy code
inline fun <R> catch(f: () -> R, predicate: (Throwable) -> Boolean): Either<Throwable, R> =
  try {
    f().right()
  } catch (t: Throwable) {
    t.nonFatalOrThrow()
    if (predicate(t.nonFatalOrThrow())) t.left()
    else throw t
  }
So we can use it like
catch(f) {it as SpecificException}
👍 1
g
i’m a beginner and i found myself using
Copy code
inline fun <A, B> Either<A, B>.filterLeft(predicate: (A) -> Boolean, default: () -> B): Either<A, B> =
    swap().filterOrElse(predicate, default).swap()
to handle it in the flow, but i would like to improve this so i think also your
catch
is great
👍 1
s
@thanh wouldn’t
as
result in a class cast exception? I ended up playing with a version that used a type parameter, but it requires specifying
R
explicitly as well.