Recently, I have implemented API with graphql-ruby. So, I searched for best practices for error handling in graphql. I'm just getting started, so there's a better way! We are looking for comments.
Before we move on to implementing error handling, there are several types of errors that we will introduce. The following articles are very easy to understand and organized, so I refer 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 system: 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: Error details and workarounds on the front side (this area may change depending on the requirements)
The point is that the abnormal system displays the message of the fixed template, but the quasi-abnormal system sends the message from the API. The main issue is how to implement this requirement.
In graphql-ruby, in case of error, json with 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 null is included in the argument passed on the front side.
The above error can also be generated by writing the code directly as follows.
sample.ruby
raise GraphQL::ExecutionError.new('error message', extensions: {code: "ERROR_CODE"})
From the above specifications, it can be seen that errors are returned as the return value for abnormal errors. So what about the quasi-abnormal system? The requirements for the quasi-abnormal system are as follows.
--Pass the error message to be displayed on the screen --The front can be judged as a quasi-abnormal error
The first requirement is ok because you can pass an error message by raising the graphql error above. However, as it is, it cannot be distinguished from an abnormal error on the front side.
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, an error message is displayed as it is. Other than that, by displaying the template message, it is possible to separate the processing of the abnormal system and the quasi-abnormal system.
graphql-ruby official How to handle errors in GraphQL
Recommended Posts