SC

Scala Error Handling

Functional error handling in Scala using Either, Try, Option, and validated error accumulation

Details

Language / Topic
scalaScala
Category
Error Handling

Rules

balanced
- Use `Either[AppError, A]` as the primary error channel for business logic — put errors on the `Left` and results on the `Right`.
- Use `Try(computation)` to wrap exceptions from Java interop into a safe `Success`/`Failure` type without try/catch blocks.
- Never call `.get` on `Option` or `Try` in production code — use `.getOrElse`, `.fold`, or pattern match to handle the absent case.
- Define a sealed `AppError` hierarchy with `case class`/`case object` variants for each distinct failure mode — avoid `String`-typed errors.
- Use `cats.data.Validated` (or `EitherNel`) for error accumulation in validation logic — it collects all failures instead of stopping at the first.
- Use `flatMap` chains or `for`-comprehensions to propagate `Either` errors without nesting — left values short-circuit the chain automatically.
- Log errors with structured context at boundaries where they are caught; avoid logging and re-throwing which creates duplicate noise.