| title | Matching on Success and Failure with match | |||||||
|---|---|---|---|---|---|---|---|---|
| id | pattern-match | |||||||
| skillLevel | beginner | |||||||
| applicationPatternId | error-management | |||||||
| summary | Use match to handle both success and failure cases in a single, declarative place for Effect, Option, and Either. | |||||||
| tags |
|
|||||||
| rule |
|
|||||||
| related |
|
|||||||
| author | PaulJPhilp | |||||||
| lessonOrder | 2 |
Use the match combinator to handle both success and failure cases in a single, declarative place.
This works for Effect, Option, and Either, and is the foundation for robust, readable error handling and branching.
Pattern matching with match keeps your code clear and type-safe, ensuring you handle all possible outcomes.
It avoids scattered if/else or switch statements and makes your intent explicit.
import { Effect, Option, Either } from "effect";
// Effect: Handle both success and failure
const effect = Effect.fail("Oops!").pipe(
Effect.match({
onFailure: (err) => `Error: ${err}`,
onSuccess: (value) => `Success: ${value}`,
})
); // Effect<string>
// Option: Handle Some and None cases
const option = Option.some(42).pipe(
Option.match({
onNone: () => "No value",
onSome: (n) => `Value: ${n}`,
})
); // string
// Either: Handle Left and Right cases
const either = Either.left("fail").pipe(
Either.match({
onLeft: (err) => `Error: ${err}`,
onRight: (value) => `Value: ${value}`,
})
); // stringExplanation:
Effect.matchlets you handle both the error and success channels in one place.Option.matchandEither.matchlet you handle all possible cases for these types, making your code exhaustive and safe.
Using nested if/else or switch statements to check for success/failure, or ignoring possible error/none/left cases, which leads to brittle and less readable code.