Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expose GraphqlExceptions using spring boot starter

When using the Spring Boot starter for graphql, all of the exceptions thrown while data fetching appear in the output console as "Internal Server Error(s) while executing query" I would like the just the e.message() string of the GraphQLException I throw to come out of the "message" part of the error field in Graphql so that the front end of this API can see what went wrong.

I've googled this to no avail. Most people expose the errors by editing the Servlet, but since I'm using the Spring Boot starter I cannot do this easily. I know that the graphql-servlet used by starter has a class called DefaultGraphQLErrorHandler found here but I do not know how to override or change it or just somehow get those errors to display.

I tried overriding the SimpleDataFetcherExceptionHandler in graphql, creating a CustomException that overrides GraphQlException but neither worked, the SimpleDataFetcherExceptionHandler implementation was never called during a debug.

I only ever see this:

Graphql error output

Thanks

like image 275
Young_Maker Avatar asked Dec 10 '22 06:12

Young_Maker


1 Answers

So I figured this out. I had to provide a custom implementation of a GraphQLErrorHandler and add it to the list of beans by marking as a @Component. I then overrided the processErrors() function in the error handler. When marked as a component, this bean was autowired into the graphql serverlet configurator in the graphql spring boot starter package, replacing the default one.

the CustomGraphQlErrorHandler I added is seen below:

import graphql.GraphQLError
import graphql.servlet.GenericGraphQLError
import graphql.servlet.GraphQLErrorHandler
import org.springframework.stereotype.Component

@Component
class CustomGraphQlErrorHandler: GraphQLErrorHandler {

    override fun processErrors(errors: MutableList<GraphQLError>?): MutableList<GraphQLError> {
        val errorList = mutableListOf<GraphQLError>()
        for(error in errors!!){
            errorList.add(GenericGraphQLError(error.message))
        }
        return errorList
    }

} 

the output looks like this now: enter image description here

like image 155
Young_Maker Avatar answered Jan 17 '23 00:01

Young_Maker