GraphQL Input Error Handling

13 Feb 2023

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,
          },
        },
      };
    },
  },
};