--- 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: - match - pattern-matching - effect - option - either - error-handling - branching rule: description: >- Use match to pattern match on the result of an Effect, Option, or Either, handling both success and failure cases declaratively. related: - pattern-matchtag - pattern-matcheffect - pattern-option-either-match author: PaulJPhilp lessonOrder: 2 --- # Matching on Success and Failure with `match` ## Guideline 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. ## Rationale 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. ## Good Example ```typescript 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 // 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}`, }) ); // string ``` **Explanation:** - `Effect.match` lets you handle both the error and success channels in one place. - `Option.match` and `Either.match` let you handle all possible cases for these types, making your code exhaustive and safe. ## Anti-Pattern 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.