Skip to content

Instantly share code, notes, and snippets.

@kenoir
Last active March 18, 2020 10:57
Show Gist options
  • Save kenoir/a0e6e9455f9e68cb511e0f268ff5e478 to your computer and use it in GitHub Desktop.
Save kenoir/a0e6e9455f9e68cb511e0f268ff5e478 to your computer and use it in GitHub Desktop.
object ErrorStates {
// Type alias to string so it compiles
type Input = String
type Output = String
sealed trait ErrorState[Context] {
val err: Option[Throwable]
val ctx: Context
}
// Some examples of error types that might crop up in the real world
// and an excuse to exercise the option in ErrorState
case class KnownErrorState(ctx: Input)
extends ErrorState[Input] {
val err = None
}
case class UnknownErrorState(e: Throwable, ctx: Input)
extends ErrorState[Input] {
val err = Some(e)
}
}
object ErrorExample {
import ErrorStates._
class FooException extends Throwable
def doSomethingThatCouldThrow(): Try[Output] = ???
def doThing(input: Input): Either[ErrorState[Input], Output] = {
doSomethingThatCouldThrow match {
case Success(result) => Right(result)
case Failure(_: FooException) => Left(KnownErrorState(input))
case Failure(e) => Left(UnknownErrorState(e, input))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment