| title | Effectful Pattern Matching with matchEffect | |||||
|---|---|---|---|---|---|---|
| id | pattern-matcheffect | |||||
| skillLevel | intermediate | |||||
| applicationPatternId | error-management | |||||
| summary | Use matchEffect to perform effectful branching based on success or failure, enabling rich workflows in the Effect world. | |||||
| tags |
|
|||||
| rule |
|
|||||
| related |
|
|||||
| author | PaulJPhilp | |||||
| lessonOrder | 3 |
Use the matchEffect combinator to perform effectful branching based on whether an Effect succeeds or fails.
This allows you to run different Effects for each case, enabling rich, composable workflows.
Sometimes, handling a success or failure requires running additional Effects (e.g., logging, retries, cleanup).
matchEffect lets you do this declaratively, keeping your code composable and type-safe.
import { Effect } from "effect";
// Effect: Run different Effects on success or failure
const effect = Effect.fail("Oops!").pipe(
Effect.matchEffect({
onFailure: (err) => Effect.logError(`Error: ${err}`),
onSuccess: (value) => Effect.log(`Success: ${value}`),
})
); // Effect<void>Explanation:
matchEffectallows you to run an Effect for both the success and failure cases.- This is useful for logging, cleanup, retries, or any effectful side effect that depends on the outcome.
Using match to return values and then wrapping them in Effects, or duplicating logic for side effects, instead of using matchEffect for direct effectful branching.