Logging Nested Errors in a Typescript Library Using Effect

Hello!
I've been trying to find a good way to log nested errors in my library. Some functions come from external dependencies, and I’d like to retain those messages when the main application fails. I was wondering if adding the unknown cause inside the message: string is the right approach because when I use cause: unknown only, the errors do not accumulate, and the only log I get is: An error has occurred.
class MyCustomError extends Data.TaggedError("MyCustomError")<{
  cause?: unknown;
  message?: string;
}> {}

class MyExternalError extends Data.TaggedError("MyExternalError")<{
  cause?: unknown;
  message?: string;
}> {}

class MyAppError extends Data.TaggedError("MyAppError")<{
  message?: string;
  cause?: unknown;
}> {}

const external = Effect.try({
  try: () => {
    throw new Error("External Library Error");
  },
  catch: (e) =>
    new MyExternalError({
      message: `{ cause: ${e}, An external error has ocurred  }`,
      cause: e,
    }),
});

const program = Effect.gen(function* () {
  yield* external;
  yield* Effect.try({
    try: () => {
      throw new Error("my error");
    },
    catch: (e) =>
      new MyCustomError({
        message: `{ cause: ${e} , This is my custom error message }`,
      }),
  });
}).pipe(
  Effect.catchAllCause((e) => new MyAppError({ message: `${e}`, cause: e }))
);

try {
  const exit = await Effect.runPromise(program);
} catch (error) {
  console.log(error as Error);
}
const exit = await Effect.runPromiseExit(program);
if (exit._tag === "Failure") {
  console.log(exit.cause.toString());
}
Was this page helpful?