Last active
March 18, 2020 10:57
-
-
Save kenoir/a0e6e9455f9e68cb511e0f268ff5e478 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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