Skip to content

Commit

Permalink
Merge pull request #1034 from disneystreaming/dfrancoeur/middleware-fix
Browse files Browse the repository at this point in the history
Revert original behavior where middleware get all errors
  • Loading branch information
Baccata authored Jun 16, 2023
2 parents 0ca4cc9 + a342a3d commit bf80670
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,11 @@ private[http4s] class SmithyHttp4sServerEndpointImpl[F[_], Op[_, _, _, _, _], I,
httpEndpoint.matches(path)
}

private val applyMiddleware: HttpApp[F] => HttpApp[F] = middleware(endpoint)
private val applyMiddleware: HttpApp[F] => HttpApp[F] = { app =>
middleware(endpoint)(app).handleErrorWith(error =>
Kleisli.liftF(errorResponse(error))
)
}

override val httpApp: HttpApp[F] =
httpAppErrorHandle(applyMiddleware(HttpApp[F] { req =>
Expand All @@ -122,7 +126,6 @@ private[http4s] class SmithyHttp4sServerEndpointImpl[F[_], Op[_, _, _, _, _], I,
run
.recoverWith(transformError)
.map(successResponse)
.handleErrorWith(errorResponse)
}))

private def httpAppErrorHandle(app: HttpApp[F]): HttpApp[F] = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,39 @@ object ServerEndpointMiddlewareSpec extends SimpleIOSuite {
List(throwCheck, pureCheck).combineAll
}

test("server - middleware can catch spec error") {
val catchSpecErrorMiddleware = new ServerEndpointMiddleware.Simple[IO]() {
def prepareWithHints(
serviceHints: Hints,
endpointHints: Hints
): HttpApp[IO] => HttpApp[IO] = { inputApp =>
HttpApp[IO] { req =>
inputApp(req).handleError { case _: SpecificServerError =>
Response[IO]()
}
}
}
}

SimpleRestJsonBuilder
.routes(new HelloWorldService[IO] {
def hello(name: String, town: Option[String]): IO[Greeting] =
IO.raiseError(
SpecificServerError(Some("to be caught in middleware"))
)
})
.middleware(catchSpecErrorMiddleware)
.make
.toOption
.get
.apply(Request[IO](Method.POST, Uri.unsafeFromString("/bob")))
// would be 599 w/o the middleware
.flatMap(res => OptionT.pure(expect.eql(res.status.code, 200)))
.getOrElse(
failure("unable to run request")
)
}

test("server - middleware is applied") {
serverMiddlewareTest(
shouldFailInMiddleware = true,
Expand Down

0 comments on commit bf80670

Please sign in to comment.