GraphQL
Beginner
1 min read
Error Handling in Mutations
Example
# ----- Union error pattern -----
type CreateUserSuccess {
user: User!
}
type ValidationError {
field: String!
message: String!
}
type DuplicateEmailError {
email: String!
message: String!
}
union CreateUserResult =
| CreateUserSuccess
| ValidationError
| DuplicateEmailError
type Mutation {
createUser(input: CreateUserInput!): CreateUserResult!
}
# Resolver (Node.js)
# Mutation: {
# createUser: async (_, { input }) => {
# if (!isValidEmail(input.email)) {
# return { __typename: 'ValidationError',
# field: 'email', message: 'Invalid format' };
# }
# const exists = await User.findByEmail(input.email);
# if (exists) {
# return { __typename: 'DuplicateEmailError',
# email: input.email, message: 'Already registered' };
# }
# const user = await User.create(input);
# return { __typename: 'CreateUserSuccess', user };
# }
# }
# Client query handles each case:
mutation Register($input: CreateUserInput!) {
createUser(input: $input) {
... on CreateUserSuccess { user { id email } }
... on ValidationError { field message }
... on DuplicateEmailError { email message }
}
}
Related Resources
GraphQL Reference
Complete tag & property list
GraphQL How-To Guides
Step-by-step practical guides
GraphQL Exercises
Practice what you've learned
More in GraphQL