Skip to content

Commit b7cded6

Browse files
authored
Enhance documentation on error handling in GraphQL
Added section on modeling errors as data in GraphQL APIs, detailing recoverable and unrecoverable errors, and how to structure mutations and queries to handle errors effectively.
1 parent a367f08 commit b7cded6

File tree

1 file changed

+162
-0
lines changed

1 file changed

+162
-0
lines changed

src/pages/learn/response.mdx

Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,168 @@ The mutation above attempts to delete two starships in a single operation, but n
102102

103103
As with network calls to any type of API, network errors that are not specific to GraphQL may happen at any point during a request. These kinds of errors will block communication between the client and server before the request is complete, such as an SSL error or a connection timeout. Depending on the GraphQL server and client libraries that you choose, there may be features built into them that support special network error handling such as retries for failed operations.
104104

105+
### Modelling Errors as Data
106+
107+
When returning errors to API clients, it’s important that we enable clients to create recoverable scenarios for users. This can be enabled by providing the required context to clients, along with making it easy for clients to consume those errors.
108+
When modelling API errors for both queries and mutations we can follow two guiding principles:
109+
110+
- **Unrecoverable errors, returned in the errors array**
111+
These are errors that are not the users fault (developer errors), which are generally things that the user can’t recover from. For example, the user not being authenticated or a resource not being found. This will also include scenarios such as
112+
server crashes, unhandled exceptions and exhausted resources (for example, memory or CPU)
113+
114+
- **Recoverable errors (user errors), returned as data (typed errors)**
115+
These are errors that the user can recover from or where we need to communicate something to the user. For example, input validation error or the user having hit a limit on their plan for the requested operation. This approach allows us to
116+
utilise typed errors to provide context to clients, while allowing us to enforce a clear distinction between developer and user-facing errors. This ensures that only useful errors are returned as types and everything else developer facing will be
117+
returned in the errors array.
118+
119+
#### Mutations
120+
##### Modelling Errors
121+
Every mutation defined in the schema returns a Payload union - this allows mutations to return their success state, along with any user facing errors that may occur. This should follow the format of the mutation name, suffixed with Payload - e.g `{MutationName}Payload`.
122+
123+
```graphql
124+
union CreateHeroPayload = CreateHeroSuccess | ...
125+
```
126+
127+
This approach allows clients to query for the specific error types that they want to handle, as well as allow us to build a continuously evolving schema. When adding support for a new error, it should be added to the payload definition.
128+
129+
```graphql
130+
union CreateHeroPayload = CreateHeroSuccess | HeroLimitReached | HeroValidationFailed
131+
```
132+
133+
So that we have standardisation and flexibility in place for consuming errors, every typed error can implement the MutationError interface.
134+
135+
```graphql
136+
interface MutationError {
137+
message: String!
138+
}
139+
```
140+
141+
Each error that is defined will need to implement this interface. In the example below we can see the message being implemented as part of the `MutationError` contract - alongside this, each error type may also include its own information that is specific to that error. For example, in the case of a `HeroLimitReached` error, we may want to provide the hero limit for that account so that this can be communicated to the user or for a possible error type of `HeroAlreadyExists` it would be helpful to return the `Hero` to the client.
142+
143+
```graphql
144+
type HeroLimitReached implements MutationError {
145+
message: String!
146+
limit: Int!
147+
}
148+
```
149+
150+
Error types can contain more complex data if they need to - for example, if we were looking to implement a `HeroValidationError` error to be returned when invalid Post data was provided during post creation, we can then model this in a way that allows multiple field errors to be handled within the composer.
151+
152+
```graphql
153+
type FieldError {
154+
validationError: String!
155+
field: String!
156+
}
157+
158+
type HeroValidationError implements MutationError {
159+
message: String!
160+
errors: [FieldError!]!
161+
}
162+
```
163+
164+
When implementing the message field on the API to be returned in the response, this should be a human-readable string that can be displayed on the client. In most cases, clients will use the error type to display messaging themselves, but a default string will allow clients to display messages by default (see Future Proofing Error Responses below)
165+
166+
##### Consuming Errors
167+
168+
When it comes to consuming typed errors, clients can use the ... on pattern to consume specific errors being returned in the response. In some cases, clients will want to know exactly what error has occurred and then use this to communicate some information to the user, as well as possibly show a specific user-path to recover from that error. When this is the case, clients can consume the typed error directly within the mutation.
169+
Clients only need to consume the specific typed errors that they need to handle. For errors that fall outside of this required, the catch-all `... on MutationError` can be used to consume remaining errors in a generic fashion to communicate the given message to the user.
170+
171+
```graphql
172+
mutation CreateHero {
173+
createHero {
174+
... on CreateHeroSuccess {
175+
// handle fields
176+
}
177+
... on HeroLimitError {
178+
message
179+
limit
180+
}
181+
... on MutationError {
182+
message
183+
}
184+
}
185+
}
186+
```
187+
188+
If a client does not need to consume the specific error types, they can simply rely on the `MutationError` interface:
189+
190+
```graphql
191+
mutation CreateHero {
192+
createHero {
193+
... on CreateHeroSuccess {
194+
// handle fields
195+
}
196+
... on MutationError {
197+
message
198+
}
199+
}
200+
}
201+
```
202+
203+
#####Future proofing error responses
204+
205+
When mutations are first modelled in the schema it might be the case that there is not a need for any specific typed error to be defined. In future, you may add error types to the payload for a mutation, but it means that any existing clients utilising the mutation will need to update their code to consume any new errors. If you need to handle this scenario, a common mutation error type can be provided. For example, this `VoidMutationError` type will be included as a type of every mutation payload that do not include any other error types. This can then be removed in future when any user-facing error types are implemented for the payload.
206+
207+
```graphql
208+
type VoidMutationError implements MutationError {
209+
message: String!
210+
}
211+
212+
union CreateHeroPayload = CreateHeroSuccess | VoidMutationError
213+
```
214+
215+
While the API will never (and should never) explicitly return this `VoidMutationError` type, it means that when any type of MutationError is returned in future, clients will automatically receive new errors without needing to ship any changes.
216+
217+
```graphql
218+
... on MutationError {
219+
message
220+
}
221+
```
222+
223+
To benefit from this approach, client queries will need to include the resolution of the `MutationError`.
224+
225+
##### Returning non-recoverable errors
226+
227+
In cases where non-recoverable errors need to be returned in the errors array, our error resolver will utilise the GraphQLError class. This allows us to provide an additional code to provide more context to clients where needed. Unless we need other metadata in future, the extensions should not provide any other data outside of code that needs to be portrayed to the user - if data regarding the error is required to portray information to the user, please use a typed error.
228+
To enforce standards here, its good practice to define an `ErrorCode` enum which can then be provided to a function which will throw the error. This function allows you to centralise error logic and ensure that the backend is returning the correct error format for clients. Without this enforcement, it can be easy for the backend to become riddled with error codes.
229+
230+
```graphql
231+
enum ErrorCode {
232+
NOT_FOUND = 'NOT_FOUND',
233+
FORBIDDEN = 'FORBIDDEN',
234+
UNEXPECTED = 'UNEXPECTED',
235+
UNAUTHORIZED = 'UNAUTHORIZED'
236+
}
237+
```
238+
239+
```graphql
240+
function throwError(message: string, code: ErrorCode) {
241+
throw new GraphQLError(message, {
242+
extensions: {
243+
code: code,
244+
},
245+
});
246+
}
247+
```
248+
249+
#### Queries
250+
251+
In 95% of cases, GraphQL queries will only ever return either the information that was queried for, or an unrecoverable exception.
252+
253+
```graphql
254+
type Query {
255+
heros(input: HerosInput!): [Hero!]!
256+
}
257+
```
258+
259+
In the above query, a successful result would see a list of Hero types returned. Otherwise, the errors array will contain any errors that were thrown during the request.
260+
261+
However, there will be a small amount of cases where there are user-recoverable errors that may need to be returned from queries. In these cases, we should treat them the same as mutations and provide an union payload so that user-recoverable errors can be returned to the client.
262+
263+
For example, the user could be querying for data that requires them to upgrade their plan, or to update their app. These are user-recoverable errors and utilising errors as data can improve both the Developer and User experience in these scenarios.
264+
265+
While this is a likely to not be common when implementing queries, this approach allows us to return user recoverable errors when required.
266+
105267
## Extensions
106268

107269
The final top-level key allowed by the GraphQL specification in a response is the `extensions` key. This key is reserved for GraphQL implementations to provide additional information about the response and though it must be an object if present, there are no other restrictions on what it may contain.

0 commit comments

Comments
 (0)