When consuming an API, it's very helpful to be able to act on an error code
that gets returned. For example in apollo server, errors get a code attached. The total set of codes being limited, this allows you to write a single piece of error handling code on your client and use it on most queries.
I've noticed we don't do that when handling django errors; all we get is a path and a message:
The problem is that client-side, I now need to parse that error message. The only way I can know what happened is to parse the specific error message, ie do:
const response = {
data: null,
errors: [
{
message: "Organisation matching query does not exist.",
locations: [
{
line: 2,
column: 3
}
],
path: ["organisation"]
}
]
};
// Check if the specific error message exists in the errors list
const errorExists = response.errors?.some(error => error.message === "Organisation matching query does not exist.");
console.log(errorExists); // true if the message exists, false otherwise
This means we have to write custom error handling code for each query on the frontend side, which knows the specific message patterns produced by django.
The messages that are produceable currently are not included in the schema either, so you're kind of left in the dark as to what could happen error-wise. Having a set of error codes that could result from any given query (or even a set from all queries) would be massively helpful in knowing what you have to do to handle them.
My colleage @cortadocodes had the idea that django errors have a type associated with them. The example error shown above was generated on the query:
@strawberry.type()
class OrganisationQueries:
@strawberry.field
def organisation(self, handle: str) -> OrganisationType:
return Organisation.objects.get(handle=handle)
Now if you do:
try:
Organisation.objects.get(handle="not-anyones-handle")
except Organisation.DoesNotExist as e:
code = type(e).__name__ // This is "DoesNotExist"
message=str(e) // This is the message we get already
Do you think we could add this code to handled django error messages? It'd make error handling a lot more powerful, especially around auth and permissions workflows where codes like Unauthenticated
and Forbidden
could have completely generic error handling code on the client side.
@bellini666 If you think this is viable, I'm happy to sponsor the work, let's chat?
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