[Ruby] Error handling with Graphql-ruby

2 minute read

Introduction

Recently, I have implemented an API with graphql-ruby. So I sought best practices for error handling in graphql. I have just started, so there is a better way! We are looking for comments.

Error classification

Before we move on to implementing error handling, there are several types of errors, so let me introduce them. The following articles are very easy to understand and have been organized, so I am referring to them.

Concept of error handling (exception design) in Rails application

Here, it is classified into two types, abnormal system and quasi-abnormal system, as follows.

  • Abnormal: nw error or program error (system error)
  • Semi-abnormal system: Error that the creator can expect (business error)

There are the following requirements for these two types of errors.

  • Abnormal: Display template message on front side & notify developer
  • Semi-abnormal system: Front side of error content and workaround method (this area may change depending on requirements)

The key point is that the abnormal system displays messages of a fixed template, while the semi-abnormal system sends messages from the API. The main issue is how to implement this requirement.

Graphql-ruby specifications

In graphql-ruby, in case of error, json with the following errors as key is returned.

"errors": [
    {
      "message": "error message",
      "locations": [],
      "extensions": {
        "code": "ERROR_CODE"
      }
    }
  ]

This error message is mainly caused by bugs in the interface. For example, when the argument passed on the front side contains null.

The above error can be generated by writing the code directly as follows.

sample.ruby


raise GraphQL::ExecutionError.new('error message', extensions: {code: "ERROR_CODE"})

Implementation

From the above specifications, it can be seen that errors of abnormal type are returned in the return value. What about the semi-abnormal system? The requirements for the semi-abnormal system are as follows.

  • Pass an error message to display on the screen
  • The front can judge that it is a quasi-abnormal system error

The first requirement is ok because you can pass an error message in the way to raise the graphql error above. However, as it is, the front side cannot distinguish it from an abnormal error.

So I decided to customize json as follows.

sample.ruby


raise GraphQL::ExecutionError.new('error message', extensions: {customCode: "ERROR_CODE"})

It is code->customCode. On the front side, if customCode exists as a key, the error message is displayed as it is. Other than that, displaying the message of the template enables you to separate the processing of abnormal system and semi-abnormal system.

References

graphql-ruby official How to handle errors in GraphQL