{"id":37439557,"url":"https://github.com/valdemargr/catch-effect","last_synced_at":"2026-01-16T06:43:39.527Z","repository":{"id":206124468,"uuid":"707923426","full_name":"ValdemarGr/catch-effect","owner":"ValdemarGr","description":"MTL, but without the MT","archived":false,"fork":false,"pushed_at":"2024-12-28T10:00:13.000Z","size":60,"stargazers_count":14,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2024-12-28T10:24:30.690Z","etag":null,"topics":["developer-experience","functional-programming","monad-transformers"],"latest_commit_sha":null,"homepage":"","language":"Scala","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ValdemarGr.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-10-21T01:55:12.000Z","updated_at":"2024-12-28T10:00:16.000Z","dependencies_parsed_at":"2023-11-18T16:26:46.971Z","dependency_job_id":"7defbf82-6882-4f67-ad2b-4024c55e902a","html_url":"https://github.com/ValdemarGr/catch-effect","commit_stats":{"total_commits":35,"total_committers":1,"mean_commits":35.0,"dds":0.0,"last_synced_commit":"8a13ef7f67d2212ab8e25894cf841202781d17bd"},"previous_names":["valdemargr/catch-effect"],"tags_count":3,"template":false,"template_full_name":null,"purl":"pkg:github/ValdemarGr/catch-effect","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ValdemarGr%2Fcatch-effect","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ValdemarGr%2Fcatch-effect/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ValdemarGr%2Fcatch-effect/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ValdemarGr%2Fcatch-effect/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ValdemarGr","download_url":"https://codeload.github.com/ValdemarGr/catch-effect/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ValdemarGr%2Fcatch-effect/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28477919,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-16T06:30:42.265Z","status":"ssl_error","status_checked_at":"2026-01-16T06:30:16.248Z","response_time":107,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["developer-experience","functional-programming","monad-transformers"],"created_at":"2026-01-16T06:43:38.836Z","updated_at":"2026-01-16T06:43:39.522Z","avatar_url":"https://github.com/ValdemarGr.png","language":"Scala","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Catch effect \u003ca href=\"https://typelevel.org/cats/\"\u003e\u003cimg src=\"https://typelevel.org/cats/img/cats-badge.svg\" height=\"40px\" align=\"right\" alt=\"Cats friendly\" /\u003e\u003c/a\u003e\nCatch effect is a small library that facilitates MTL-like programs, without the need for monad transformers, but just an effect type like `IO`.\n\nCatch effect is built on top of [Vault](https://github.com/typelevel/vault), which is a map that can hold values of different types.\n\n## Installation\n```scala\n\"io.github.valdemargr\" %% \"catch-effect\" % \"0.1.2\"\n```\n\n## Context\nContext can create instances of `Local`.\n`Local` provides the ability to run an effect given some input and modify the input.\n\nThe MTL counterpart of `Context` is `Kleisli`/`ReaderT`, (`A =\u003e F[B]` for the uninitiated).\n`Context` is a building block for the more interesting `Catch` sturcture described below.\n\nIf you are using `cats-effect` and you are familiar with `IOLocal`, then `Context` should be feel familiar.\n\nYou can construct an instance of `Context` in various ways, here is one using `cats-effect`.\n```scala\nContext.ioContext: IO[Context[IO]]\n```\n\n### Example\nWhen you have an instance of `Context` in scope, new `Local` instances can be spawned on the fly.\n```scala\ntype Auth = String\ndef authorizedRoute(L: Local[IO, Auth]): IO[Unit] = \n  for {\n    user \u003c- L.ask\n    _ \u003c- Console[IO].println(s\"doing user op with $user\")\n    _ \u003c- L.local{\n      L.ask.flatMap{ user =\u003e\n        Console[IO].println(s\"doing admin operation with $user\")\n      }\n    }(_ =\u003e \"admin\")\n    user \u003c- L.ask\n    _ \u003c- Console[IO].println(s\"doing user op with $user again\")\n  } yield ()\n\ndef run(C: Context[IO]): IO[Unit] = \n  C.use(\"user\")(authorizedRoute)\n```\nRunning the program yields:\n```scala\nContext.ioContext.flatMap(C =\u003e run(C))\n// doing user op with user\n// doing admin operation with admin\n// doing user op with user again\n```\n\n### Other ways of constructing Context\nThere are several other ways to construct `Context` in the case that you are not working in `IO`.\nFor instance, if you are working in `Kleisli` a natural implementation exists.\n```scala\nContext.kleisli[IO]: Context[Kleisli[IO, Vault, *]]\n```\nOr for any instance of `Local[F, Vault]`.\n```scala\nimplicit lazy val L: Local[IO, Vault] = ???\nContext.local[IO]\n```\n\n## Catch\n`Catch` is responsible for throwing and catching errors.\nThe MTL counterpart of `Catch` is `EitherT`.\n`Catch` can introduce new ad-hoc error channels that are independent of eachother.\nThere are various ways to construct a catch, but the simplest (given that you're working in `cats-effect`) is the following.\n```scala\nCatch.ioCatch: IO[Catch[IO]]\n```\n\n### Example in `IO`\nIf you work in `IO`, the usage of `Catch` becomes simpler.\n`IOCatch` provides a utility to immediately create a `Handle` instance.\n```scala\nsealed trait UserError\ncase object WeakPassword extends UserError\ndef verifyUser(password: String)(R: Raise[IO, UserError]): IO[Unit] =\n  for {\n    _ \u003c- Console[IO].println(\"verifying user\")\n    _ \u003c- R.raiseIf(WeakPassword)(password.length \u003c 8)\n    _ \u003c- Console[IO].println(\"user verified\")\n  } yield ()\n```\nRunning the program yields:\n```scala\n(\n  IOCatch[UserError](verifyUser(\"pass\")(_)),\n  IOCatch[UserError](verifyUser(\"supersafepassword123\")(_))\n).tupled\n// verifying user\n// verifying user\n// user verified\n// (Left(WeakPassword),Right(()))\n```\n\n### Example for any effect\nWith an instance of `Catch` in scope, you can create locally scoped domain-specific errors.\n```scala\nsealed trait DomainError\ncase object MissingData extends DomainError\ndef domainFunction[F[_]: Console](R: Raise[F, DomainError])(implicit F: Async[F]) = \n  for {\n    xs \u003c- F.delay((0 to 10).toList)\n    _ \u003c- R.raiseIf(MissingData)(xs.nonEmpty)\n    _ \u003c- Console[F].println(\"Firing the missiles!\")\n  } yield ()\n\ndef doDomainEffect[F[_]: Catch: Async: Console]: F[Unit] = \n  Catch[F].use[DomainError](domainFunction[F]).flatMap{\n    case Left(MissingData) =\u003e Console[F].println(\"Missing data!\")\n    case Right(()) =\u003e Console[F].println(\"Success!\")\n  }\n```\nRunning this program yields:\n```scala\nCatch.ioCatch.flatMap(implicit C =\u003e doDomainEffect[IO])\n// Missing data!\n```\n\n`Catch`, `Raise` and `Handle` instances are well behaved when nested and can raise errors on their completely isolated error channels.\n\n`Handle`'s API can also facilitate parallel gathering of errors, like `EitherT`'s `Parallel` instance.\n```scala\ntrait CreateUserError\ncase object InvalidEmail extends CreateUserError\ncase object InvalidPassword extends CreateUserError\ndef createUser[F[_]: Console: Sync](idx: Int)(R: Raise[F, CreateUserError]): F[Unit] = \n  for {\n    _ \u003c- R.raiseIf(InvalidEmail)(idx % 2 == 0)\n    _ \u003c- R.raiseIf(InvalidPassword)(true)\n    _ \u003c- Console[F].println(s\"Created user!\")\n  } yield ()\n\ndef createUserBatch[F[_]: Console: Sync: Catch]: F[Unit] =\n  Catch[F].use[List[CreateUserError]]{ implicit H =\u003e \n    val one = H.contramap[CreateUserError](List(_))\n    implicit val P: Parallel[F] = H.accumulatingParallelForApplicative\n    (0 to 10).toList.parTraverse(createUser[F](_)(one))\n  }.flatMap{\n    case Left(errors) =\u003e Console[F].println(s\"Errors: ${errors.map(x =\u003e \"\\n// \" + x.toString()).mkString(\"\")}\")\n    case Right(_) =\u003e Console[F].println(\"Success!\")\n  }\n```\nRunning the program yields:\n```scala\nCatch.ioCatch.flatMap(implicit C =\u003e createUserBatch[IO])\n// Errors: \n// InvalidEmail\n// InvalidPassword\n// InvalidEmail\n// InvalidPassword\n// InvalidEmail\n// InvalidPassword\n// InvalidEmail\n// InvalidPassword\n// InvalidEmail\n// InvalidPassword\n// InvalidEmail\n```\n\n### Incorrect usage of Catch\n`Catch` builds uppon cancellation of effects.\nAs such, any invocation of `raise` (or it's other variants) must not occur in an `uncancelable` block.\nThis is usually not an issue for most (if not all) applications, but must be respected regardless.\n```scala\n// Raise cannot cancel itself when in an uncancelable block\nIOCatch[String](r =\u003e IO.uncancelable(_ =\u003e r.raise(\"error\")))\n```\n\n### Other ways of constructing Catch\n1. Catch can occur for an instance of `Handle[F, Vault]` (or `EitherT[F, Vault, A]`)\n2. Catch can occur for an instance of `Local[F, Vault]` (or `Kleisli[F, Vault, A]`) and `Concurrent[F]` via cancellation\n\nAn interestingly, you can in fact construct `Catch` if you have `Context` and `Concurrent`.\n```scala\nimport org.typelevel.vault._\ntrait MyError\ndef example[F[_]: Context: Concurrent] =\n  Context[F].use(Vault.empty){ implicit L =\u003e \n    Catch.fromLocal[F].use[MyError]{ implicit R =\u003e \n      Concurrent[F].unit\n    }\n  }\n```\n\n## Unsafe use of algebras\nLike any resources, the structures defined in this library are only well-behaved within a scope.\nUse outside of their scope is considered an error and will be detected (like a resource leak).\n\nConsider the following examples that lead to errors.\n```scala\ndef catchError(ctch: Catch[IO]) =\n  ctch.use[String](x =\u003e IO(x)).flatMap{ e =\u003e \n    e.traverse(_.raise(\"Oh no!\"))\n  }\n\ndef contextError(ctx: Context[IO]) = \n  ctx.use(\"initial\")(x =\u003e IO(x)).flatMap{ L =\u003e \n    L.ask\n  }\n```\nRunning the Catch example:\n```scala\nCatch.ioCatch.flatMap(catchError)\n// catcheffect.Catch$RaisedWithoutHandler: I think you might have a resource leak.\n// You are trying to raise at README.md:234,\n// but this operation occured outside of the scope of the handler.\n// Either widen the scope of your handler or don't leak the algebra.\n// The handler was defined at README.md:233\n```\nAnd then then Context example:\n```scala\nContext.ioContext.flatMap(contextError)\n// catcheffect.Context$NoHandlerInScope: A Local operator was invoked outside of it's handler.\n// The Local operator was invoked at README.md:240.\n// The handler for this Local instance was defined at README.md:239.\n// \n// You may have leaked the Local algebra by accident.\n// This can be casued by functions of similar form as the following.\n// ```\n//   trait Algebra[F[_]] {\n//     def doSomething: F[Unit]\n//   }\n//   def make[F[_]](loc: Local[F, A]): F[Algebra[F]] = ???\n//   // ...\n//   Context[F].use(initialValue) { loc =\u003e \n//      make[F](loc)\n//   }.flatMap(algebra =\u003e algebra.doSomething)\n// ```\n// \n// Either move your handler further out.\n// ```\n//   Context[F].use(initialValue) { loc =\u003e \n//      make[F](loc)\n//        .flatMap(algebra =\u003e algebra.doSomething)\n//   }\n// ```\n// \n// Or use the low-level `Context[F].allocated` method.\n// ```\n//   Context[F].allocated[A].flatMap { loc =\u003e \n//      val fk = loc.setK(initialValue)\n//      fk {\n//          make[F](loc).mapK(fk)\n//      }\n//   }.flatMap(algebra =\u003e algebra.doSomething)\n// ```\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvaldemargr%2Fcatch-effect","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fvaldemargr%2Fcatch-effect","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvaldemargr%2Fcatch-effect/lists"}