0
0
GraphqlDebug / FixBeginner · 4 min read

How to Handle Errors in GraphQL Resolver Correctly

In GraphQL, handle errors in a resolver by throwing an Error or returning a rejected Promise. This lets GraphQL catch the error and send it in the errors field of the response without crashing the server.
🔍

Why This Happens

Errors happen in resolvers when something goes wrong, like a database failure or invalid input. If you don't handle these errors properly, your server might crash or send incomplete responses.

javascript
const resolvers = {
  Query: {
    user: (parent, args, context) => {
      const user = database.findUserById(args.id);
      if (!user) {
        return null; // No error thrown here
      }
      return user;
    }
  }
};
Output
Response returns null for missing user without error details, causing client confusion.
🔧

The Fix

Throw an Error inside the resolver when something goes wrong. GraphQL will catch this and include the error message in the response's errors array. This informs the client clearly about the problem.

javascript
const resolvers = {
  Query: {
    user: (parent, args, context) => {
      const user = database.findUserById(args.id);
      if (!user) {
        throw new Error('User not found');
      }
      return user;
    }
  }
};
Output
{ "data": { "user": null }, "errors": [ { "message": "User not found", "locations": [...], "path": ["user"] } ] }
🛡️

Prevention

Always validate inputs and handle possible failure points by throwing errors or returning rejected promises. Use try-catch blocks for async resolvers and consider custom error classes for clearer error types. Enable logging to track errors and use tools like graphql-shield for authorization errors.

⚠️

Related Errors

Common related errors include unhandled promise rejections in async resolvers and returning incorrect types instead of errors. Fix these by always returning or throwing errors properly and using async/await with try-catch.

Key Takeaways

Always throw an Error in resolvers to signal problems to GraphQL.
GraphQL sends thrown errors in the response's errors field without crashing.
Use try-catch in async resolvers to handle promise rejections.
Validate inputs early to avoid unnecessary errors.
Log errors for easier debugging and monitoring.