Skip to content

Instantly share code, notes, and snippets.

@hamnis
Last active February 26, 2021 17:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hamnis/d0ef3901ba6b9c0a68586177f81ee5f8 to your computer and use it in GitHub Desktop.
Save hamnis/d0ef3901ba6b9c0a68586177f81ee5f8 to your computer and use it in GitHub Desktop.
import cats.implicits._
import cats.MonadError
import cats.data.{Kleisli, OptionT}
import org.http4s._
object ErrorHandling {
def apply[F[_], G[_]](
k: Kleisli[F, Request[G], Response[G]],
pf: Request[G] => PartialFunction[Throwable, F[Response[G]]] = inDefaultServiceErrorHandler[F, G]
)(implicit F: MonadError[F, Throwable]): Kleisli[F, Request[G], Response[G]] =
Kleisli { req =>
k.run(req).handleErrorWith { e =>
pf(req).lift(e) match {
case Some(resp) => resp
case None => F.raiseError(e)
}
}
}
def httpRoutes[F[_]: MonadError[*[_], Throwable]](
httpRoutes: HttpRoutes[F],
pf: Request[F] => PartialFunction[Throwable, OptionT[F, Response[F]]] = inDefaultServiceErrorHandler[F, OptionT[F, *]]
): HttpRoutes[F] =
apply(httpRoutes, pf)
def httpApp[F[_]: MonadError[*[_], Throwable]](
httpApp: HttpApp[F],
pf: Request[F] => PartialFunction[Throwable, F[Response[F]]] = inDefaultServiceErrorHandler[F, F]
): HttpApp[F] =
apply(httpApp, pf)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment