Error Handling

All applications fail, and GraphQL is no different. Some clients may ask for information that’s not available or execute a forbidden action. In this chapter, you’ll understand how GraphQL and Graphene address these issues.

Schema Errors

Being a language with a strong type system, GraphQL can predetermine if a query is valid. All the fields from queries and mutations have a strong type, so requesting and inputting wrong data will generate an error.

Try it out! In the links query, ask for the cheese field and see how GraphQL returns back an error:

ask for the cheese field and see how GraphQL returns back an error

Graphene Errors

On the application level, you can use the GraphQLError class or the good and old Python exceptions.

You already used the raise Exception('message') through the code, for example, when checking if the user or link were valid before creating a vote. Let’s try the other one!

On #1 and #2 the code raises an exception – using two different exception classes – but giving the same result, stopping its execution and returning the message between parentheses.

Try to vote in an invalid link and see what happens:

vote in an invalid link

Unlock the next chapter
Why can GraphQL predetermine if a query is valid?
GraphQL language has a strong type system
GraphQL is a new language
GraphQL can be implemented in various languages
GraphQL has security built-in