https://kotlinlang.org logo
#http4k
Title
# http4k
a

Arnab

07/25/2022, 10:35 AM
I was wondering about
LensFailure
for the graphQL module. The following is the code for the graphQL handler:
Copy code
fun <T> graphQL(handler: GraphQLWithContextHandler<T>,
                getContext: (Request) -> T,
                badRequestFn: (LensFailure) -> Response = { Response(BAD_REQUEST) }
): RoutingHttpHandler = routes(POST to {
    try {
        Response(OK).with(responseLens of handler(requestLens(it), getContext(it)))
    } catch (e: LensFailure) {
        badRequestFn(e)
    }
})
How do I throw an error in my graphql handlers in such a way that the
badRequestFn
can process it? Is it not possible to throw my own custom Exceptions directly or do I need to wrap them somehow so they become a
LensFailure
type?
I can obviously modify the function written above to process the
Exception
type rather than
LensFailure
but I’m hoping to leverage the library first and foremost 🙂
d

dave

07/25/2022, 1:29 PM
At the moment you can't. I wouldn't use the same mechanism TBH, so I'd either rewrite the function (it is only a couple of lines), or just wrap the handler in your own Filter which intercepted those exceptions 🙂
a

Arnab

07/27/2022, 2:25 PM
I ended up doing this:
Copy code
object CatchAllGraphQLExceptionsFilter {
  operator fun invoke(exceptionHandler: ExceptionHandler): Filter = Filter { next ->
    {
      try {
        next(it)
      } catch (e: Exception) {
          exceptionHandler(e)
      }
    }
  }
}

...
"/graphql" bind POST to CatchAllGraphQLExceptionsFilter(baseExceptionHandler).then(
      graphQL(
        BaseHandler,
        ::contextFnGithub
      )
    )