Skip to content

Latest commit

 

History

History
60 lines (48 loc) · 1.8 KB

File metadata and controls

60 lines (48 loc) · 1.8 KB
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
matchEffect
pattern-matching
effect
branching
error-handling
rule
description
Use matchEffect to pattern match on the result of an Effect, running effectful logic for both success and failure cases.
related
pattern-match
pattern-matchtag
pattern-catchtag
author PaulJPhilp
lessonOrder 3

Effectful Pattern Matching with matchEffect

Guideline

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.

Rationale

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.

Good Example

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:

  • matchEffect allows 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.

Anti-Pattern

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.