I've been struggling for a while with decent error handling that would allow me to be proficient on both the backend and frontend sides.
I started from Strawberry's official documentation: Dealing with errors.
Eventually, I tried using the "__typename
/ ... on <T> {
" syntax to provide clients some custom information but I didn't like it.
IMHO, this method makes the syntax very verbose by forcing you to copy & paste a lot of code between queries/mutations.
So I started looking for other alternatives...
After a while, I ended up on the official GraphQL Specification which talked about errors and the extensions
key that can be freely used by developers to provide additional information about the errors that occurred.
Β«How can I use that key in Strawberry?Β»
Strawberry's docs didn't really say nothing about that...
Even if it seems to be perfectly possible and supported by the library.
At the end, in fact, I figured it out and that's why I'm opening this issue...
I think one of the major features has been completely omitted.
Here's some using example:
exceptions.py
from strawberry.exceptions import StrawberryGraphQLError
class AuthenticationException(StrawberryGraphQLError):
def __init__(self, message, error_code: str = None, error_id: str = None, **kwargs):
super().__init__(message, **kwargs)
self.extensions['error_code'] = error_code
self.extensions['error_id'] = error_id
mutations.py
import strawberry
from .exceptions import AuthenticationException
@strawberry.type
class Mutation:
@strawberry.mutation
def login(self, username: str, password: str) -> User:
user: Optional[User] = authenticate(username, password)
if user is None:
raise AuthenticationException("The provided credentials are invalid",
error_code='INVALID_CREDENTIALS',
error_id='0x00000111')
return user
schema = strawberry.Schema(mutation=Mutation)
mutation Login {
login(username: "", password: "") {
user {
id
email
username
}
}
}
{
"data": null,
"errors": [
{
"message": "The provided credentials are invalid",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"login"
],
"extensions": {
"error_id": "0x00000111",
"error_code": "INVALID_CREDENTIALS"
}
}
]
}
This allowed me to fix my error-handling issues and polish my implementation with some nice-n-clean syntax.
To me, it deserves to be documented as well. π
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too