Effect CommunityEC
Effect Community9mo ago
21 replies
Devin

Handling multiple tagged errors in a single branch

I have a setup that is something like this, and I want to handle both ExceptionA and ExceptionB in one Match branch. Is there a matcher for this or do I have to structure my errors differently?

import { Console, Data, Effect, Match, Random } from 'effect'

class ExceptionA extends Data.TaggedError('ExceptionA') {}
class ExceptionB extends Data.TaggedError('ExceptionB') {}

type ExceptionAOrB = ExceptionA | ExceptionB

class ExceptionC extends Data.TaggedError('ExceptionC') {}

const fail = Effect.gen(function* () {
  const random = yield* Random.next

  if (random > 0.5) {
    yield* new ExceptionA()
  }

  if (random > 0.25) {
    yield* new ExceptionB()
  }

  yield* new ExceptionC()
})

const handleError = (error: ExceptionAOrB | ExceptionC) => {
  return Match.value(error).pipe(
    Match.tagsExhaustive({
      ExceptionA: () => handleAOrB, // <-- I want to handle both of
      ExceptionB: () => handleAOrB, // <-- these cases in one branch
      ExceptionC: () => handleC,
    })
  )
}

const handleAOrB = Console.log('Handling Exception A or B')
const handleC = Console.log('Handling Exception C')

const main = Effect.gen(function* () {
  yield* fail
}).pipe(Effect.catchAll(handleError))
Was this page helpful?