Effect CommunityEC
Effect Community6mo ago
36 replies
nashetime

How to write generic reusable Effect.catchTag handlers for TaggedErrors

Problem:
I have repetitive Effect.catchTag error handling code in my API handlers. I want to refactor it into reusable helpers, but when I try, the TypeScript typechecker complains and I can’t get the types right.

What I’d like:
Define typed, reusable error handlers once, then compose them easily in pipe or Effect.catchTags, e.g.:

.pipe(Effect.catchTags(
  catchDatabaseError,
  catchInvalidPrimaryKeyError,
  catchEntityNotFoundError,
));

I want to avoid repeating full generic signatures for Effect.catchTag every time.

Current code structure (repetitive):

Effect.catchTag("DatabaseError", (err) =>
  pipe(
    Effect.log(err),
    Effect.flatMap(() => new InternalServerError()),
  ),
)

Effect.catchTag("InvalidPrimaryKeyError", () => new BadRequest())

Effect.catchTag("EntityNotFoundError", () => new NotFound())


Used like this in handlers:

return repo.findOne({ id }).pipe(
  Effect.catchTag("DatabaseError", (err) =>
    pipe(Effect.log(err), Effect.flatMap(() => new InternalServerError()))
  ),
  Effect.catchTag("InvalidPrimaryKeyError", () => new BadRequest()),
  Effect.catchTag("EntityNotFoundError", () => new NotFound()),
);
Was this page helpful?