Effect CommunityEC
Effect Community10mo ago
4 replies
Devin

Is there a way to get a stack trace to the error source via Cause?

I have a situation where a NoSuchElementException can be raised in multiple places and I want to know which failed. I know that I can map the errors and annotate them, but I want to know if there is a way to just a detailed stack trace and avoid having to manually "annotate" each error. Even when I use "Cause" via catchAllCause, the stack trace just points to Effect internals and doesn't find its way back to either operation trying to make "item" or "item2" below. Thanks in advance!

type Item = { id: string }

const someOption = Option.some('foo')

const foo = (items: Item[]) =>
  Effect.gen(function* () {
    // Could fail with NoSuchElementException
    const item = yield* Array.findFirst(items, (i) => i.id === 'foo')

    // Could also fail with NoSuchElementException
    const item2 = yield* someOption

    return item.id.concat(item2)
  })

const result = foo([{ id: '1' }, { id: '2' }]).pipe(
  // Error is NoSuchElementException, but no indication which
  // I want this error to be detailed with a stack trace to which
  // NoSuchElementException was raised
  Effect.catchAll((error) =>
    Effect.sync(() => {
      // Send error to error monitoring service
    })
  )
)


And I'm hoping to avoid having to do this to "label" each error:

const foo = (items: Item[]) =>
  Effect.gen(function* () {
    // Could fail with NoSuchElementException
    const item = yield* Array.findFirst(items, (i) => i.id === 'foo').pipe(
      Effect.mapError(() => 'Failed to find item with id foo' as const)
    )

    // Could also fail with NoSuchElementException
    const item2 = yield* someOption.pipe(
      Effect.mapError(() => 'Failed to get item from someOption' as const)
    )

    return item.id.concat(item2)
  })
Was this page helpful?