File: errors.md

package info (click to toggle)
strawberry-graphql 0.306.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 18,176 kB
  • sloc: javascript: 178,052; python: 65,643; sh: 33; makefile: 25
file content (320 lines) | stat: -rw-r--r-- 6,702 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
---
title: Dealing with errors
---

# Dealing with errors

There are multiple different types of errors in GraphQL and each can be handled
differently.

In this guide we will outline the different types of errors that you will
encounter when building a GraphQL server.

**Note**: By default Strawberry will log all execution errors to a
`strawberry.execution` logger:
[/docs/types/schema#handling-execution-errors](../types/schema#handling-execution-errors).

## GraphQL validation errors

GraphQL is strongly typed and so Strawberry validates all queries before
executing them. If a query is invalid it isn’t executed and instead the response
contains an `errors` list:

<CodeGrid>

```graphql
{
  hi
}
```

```json
{
  "data": null,
  "errors": [
    {
      "message": "Cannot query field 'hi' on type 'Query'.",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": null
    }
  ]
}
```

</CodeGrid>

Each error has a message, line, column and path to help you identify what part
of the query caused the error.

The validation rules are part of the GraphQL specification and built into
Strawberry, so there’s not really a way to customize this behavior. You can
disable all validation by using the
[DisableValidation](../extensions/disable-validation) extension.

## GraphQL type errors

When a query is executed each field must resolve to the correct type. For
example non-null fields cannot return None.

```python
import strawberry


@strawberry.type
class Query:
    @strawberry.field
    def hello() -> str:
        return None


schema = strawberry.Schema(query=Query)
```

<CodeGrid>

```graphql
{
  hello
}
```

```json
{
  "data": null,
  "errors": [
    {
      "message": "Cannot return null for non-nullable field Query.hello.",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": ["hello"]
    }
  ]
}
```

</CodeGrid>

Each error has a message, line, column and path to help you identify what part
of the query caused the error.

## Unhandled execution errors

Sometimes a resolver will throw an unexpected error due to a programming error
or an invalid assumption. When this happens Strawberry catches the error and
exposes it in the top level `errors` field in the response.

```python
import strawberry


@strawberry.type
class User:
    name: str


@strawberry.type
class Query:
    @strawberry.field
    def user() -> User:
        raise Exception("Can't find user")


schema = strawberry.Schema(query=Query)
```

<CodeGrid>

```graphql
{
  user {
    name
  }
}
```

```json
{
  "data": null,
  "errors": [
    {
      "message": "Can't find user",
      "locations": [
        {
          "line": 2,
          "column": 2
        }
      ],
      "path": ["user"]
    }
  ]
}
```

</CodeGrid>

## Partial responses for failed resolvers

By default, GraphQL allows partial responses when a resolver fails. This means
that successfully resolved fields are still returned alongside errors. However,
this applies only when the erroneous field is defined as optional.

Consider the following example:

```python
from typing import Optional
import strawberry


@strawberry.type
class Query:
    @strawberry.field
    def successful_field(self) -> Optional[str]:
        return "This field works"

    @strawberry.field
    def error_field(self) -> Optional[str]:
        raise Exception("This field fails")


schema = strawberry.Schema(query=Query)
```

<CodeGrid>

```graphql
{
  successfulField
  errorField
}
```

```json
{
  "data": {
    "successfulField": "This field works",
    "errorField": null
  },
  "errors": [
    {
      "message": "This field fails",
      "locations": [{ "line": 3, "column": 3 }],
      "path": ["errorField"]
    }
  ]
}
```

</CodeGrid>

The response includes both successfully resolved data and error details,
demonstrating GraphQL's ability to return partial results.

## Expected errors

If an error is expected then it is often best to express it in the schema. This
allows the client to deal with the error in a robust way.

This could be achieved by making the field optional when there is a possibility
that the data won’t exist:

```python
from typing import Optional
import strawberry


@strawberry.type
class Query:
    @strawberry.field
    def get_user(self, id: str) -> Optional[User]:
        try:
            user = get_a_user_by_their_ID
            return user
        except UserDoesNotExist:
            return None
```

When the expected error is more complicated it’s a good pattern to instead
return a union of types that either represent an error or a success response.
This pattern is often adopted with mutations where it’s important to be able to
return more complicated error details to the client.

For example, say you have a `registerUser` mutation where you need to deal with
the possibility that a user tries to register with a username that already
exists. You might structure your mutation type like this:

```python
import strawberry

from typing import Annotated, Union


@strawberry.type
class RegisterUserSuccess:
    user: User


@strawberry.type
class UsernameAlreadyExistsError:
    username: str
    alternative_username: str


# Create a Union type to represent the 2 results from the mutation
Response = Annotated[
    Union[RegisterUserSuccess, UsernameAlreadyExistsError],
    strawberry.union("RegisterUserResponse"),
]


@strawberry.mutation
def register_user(username: str, password: str) -> Response:
    if username_already_exists(username):
        return UsernameAlreadyExistsError(
            username=username,
            alternative_username=generate_username_suggestion(username),
        )

    user = create_user(username, password)
    return RegisterUserSuccess(user=user)
```

Then your client can look at the `__typename` of the result to determine what to
do next:

```graphql
mutation RegisterUser($username: String!, $password: String!) {
  registerUser(username: $username, password: $password) {
    __typename
    ... on UsernameAlreadyExistsError {
      alternativeUsername
    }
    ... on RegisterUserSuccess {
      user {
        id
        username
      }
    }
  }
}
```

This approach allows you to express the possible error states in the schema and
so provide a robust interface for your client to account for all the potential
outcomes from a mutation.

---

## Additional resources:

[A Guide to GraphQL Errors | productionreadygraphql.com](https://productionreadygraphql.com/2020-08-01-guide-to-graphql-errors/)

[200 OK! Error Handling in GraphQL | sachee.medium.com](https://sachee.medium.com/200-ok-error-handling-in-graphql-7ec869aec9bc)