GraphQL Input Error Handling

Handle input errors with GraphQL using types, and soon to be "@oneOf" directive.

interface Error {
  message: String!
}

type User {
  username: String!
}

type Query {
  user(username: String!): User!
}

type Mutation {
  updateUser(input: UpdateUserInput!): UpdateUserResult!
}

type UpdateUserResult {
  success: UpdateUserSuccess
  error: UpdateUserError
}

type UpdateUserSuccess {
  updatedUser: User!
}

type UpdateUserError implements Error {
  message: String!
  inputErrors: UpdateUserInputErrors!
}

type UpdateUserInputErrors {
  username: String
}

input UpdateUserInput {
  username: String
}
const resolvers = {
  Query: {
    //  ...
  },
  Mutation: {
    updateUser: (_, { input: { username } }) => {
      if (username === "jamie") {
        return {
          error: {
            message: "Could not update user",
            inputErrors: {
              username: "Username is taken",
            },
          },
        };
      }

      return {
        success: {
          updatedUser: {
            username,
          },
        },
      };
    },
  },
};
Jamie Barton

Published on 13 Feb 2023 by Jamie Barton