GraphQL — error handling

I’m big fan of GraphQL. It seems that it will be next industry standard for API. It’s really easy to implement (at least in .net world) and it delivers many great features. Main issue which GraphQL solves is minimization of requests to the API server from web/native applications. Thus it’s great for SPA or native applications. More details about GraphQL you can find on the official page.

One of the issues which I had with GraphQL concept was errors/authorization handling. In the REST API each requests is run separately so it’s really easy to return information to the client about request status (we can use status codes e.g. 403 Forbidden, 404 NotFound etc.). We cannot use the same behaviour in GraphQL, becouse if one of the query fails we shouldn’t change status code for whole request. Some of queries in one request can be resolved properly some may fails, but still we have to return 200 OK status code. That’s why we have to figure out something else.

First step which I done when I come across that problem was preparing JSON which GraphQL should return.

Above we have JSON which was generated based on two queries (project and projects). Both are executed successfully thus we have in both queries StatusCode property with Success value. When one of query fails we should get response like in schema below.

Generally I boxed response which I want to return by resolver by class which contains properties:

  • StatusCode — simple code with status code — similar like HTTP status codes but written as a string like: NotFound, Forbidden etc.
  • ErrorMessage — more detailed information about error if status code is not Success.
  • Data — main data which should be returned by query.

I created ResponseGraphType class to represent type field in GraphQL.

Also we have to create Response class which should be returned by our resolvers.

Now we can use both above classes in resolver. Our GraphQL field will be ResponseGraphType<> type, and resolver should return Response object.

Also we can create base class for our resolvers (similar class to Controller class in MVC).

After this we can inherite class where we have our queries from this new class and modify a little bit our resolver. Now it’s even more readable.

After that modification GraphQL API returns exactly the same JSON like I showed at the beginnig of the story.

Now we have to do similar things when we want to return collections. First we have to add additional GraphQL type which can store arrays in the Data property.

And we can add new query and resolver for list.

Now all my request from GrapQL API is boxed with general information about each query status. Client applications can check that status and react accordingly.


If you are interested how I used GraphQL in .NET (Core) you can view source code of one of my project on GitHub.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.