Effect CommunityEC
Effect Community•3y ago•
55 replies
Jakob Norlin

[Beginner question] Building a Program with Async Functions and Error Logging

Happy beginner with everything Effect and functional programming 👋

I'm struggling with figuring out how to build up my program. What I want is basically this:
* Run async f1 with an input
* If f1 succeeds, run async f2 (with result of f1 as input)
* If f1 or f2 fails, log errors with a custom message
* Log info when both f1 and f2 starts and ends

I'm currently at this:
class F1Error {
  readonly _tag = "F1Error"
}

class F2Error {
  readonly _tag = "F2Error"
}

function f1(n: number) {
  return pipe(
    Effect.logInfo(`Starting f1: ${n}`),
    Effect.flatMap(() =>
      Effect.promise(() => (Math.random() > 0.5 ? Promise.reject(new F1Error()) : Promise.resolve(n * 2))),
    ),
    Effect.tap((res) => Effect.logInfo(`Ending f1: ${n} => ${res}`)),
  )
}

function f2(input: number) {
  return pipe(
    Effect.logInfo(`Starting f2: ${input}`),
    Effect.flatMap(() =>
      Effect.promise(() =>
        Math.random() > 0.5 ? Promise.reject(new F2Error()) : Promise.resolve(input.toLocaleString()),
      ),
    ),
    Effect.tap((res) => Effect.logInfo(`Ending f2: ${input} => ${res}`)),
  )
}

const program = pipe(
  f1(1),
  Effect.flatMap(f2),
  Effect.catchTags({
    F1Error: () => Effect.logError("F1 failed"),
    F2Error: () => Effect.logError("F2 failed"),
  }),
)

Effect.runPromise(program)


I would like to be able to code the happy path first, and then handle the errors. But with this code the program blows up when f1 or f2 fails, and errors don't get caught at all.

Could anyone give point me in the right direction?
Was this page helpful?