Exception b. Option c. Try d. Either e. Validated, Validation 2. Error Handling Tips a. Fail fast b. Avoid taking contextual value as an input c. Either vs Validated d. Abstract away Error Representation e. Asynchronous Error Handling
in Scala. ◦ Exception should be avoided though… ◦ wrap the standard library or third party libraries which potentially throw exceptions. • Completion of Future / Promise is represented with Try.
type of error representation. • Right represents the happy case and Left represents the error case by convention. • sealed trait is one of a good candidate for Left representation.
Failure or Success (ScalaZ) ◦ Similar to Either, but represents parallel errors. ◦ I’ll compare this with Either later. • Collect all errors at once. • Often used with NEL (NonEmptyList). ◦ ValidatedNel / ValidationNel type alias is prepared.
principle. • for comprehension is more readable in many cases. ◦ Scala’s “for comprehension” is not only for Monad, but works well with Monads like Option, Try, Either (right biassed). ◦ (For FP beginners) Think of Monad as classes with flatMap method. • When failure happens, it gives up subsequent computation.
Either sequential ◯ ☓ Validated (Cats) parallel ☓ (offers andThen for sequential validation) ◯ Validation (ScalaZ) parallel △ (offers separated FlatMap object) ◯ • Biased Either is Monad, so it works well with for comprehension. • Validated can be Monadic, but the behaviour is inconsistent with Applicative.
the most suitable representation for your purpose. Error Handling Tips • There’re some useful techinques for error handling. References: • https://typelevel.org/cats/ • https://speakerdeck.com/raulraja/functional-error-handling