Node.js › Error Handling

How would you implement error handling for a GraphQL API in Node.js, given GraphQL's different error-response format compared to REST?

Advanced

Answer

Unlike REST, where an error typically corresponds to a non-2xx HTTP status code, a GraphQL response almost always returns HTTP 200, with errors instead reported in a dedicated 'errors' array alongside any partial 'data' that could still be resolved -- custom error classes extending GraphQLError can attach an 'extensions' object with a machine-readable error code and additional context, letting clients distinguish error types without relying on HTTP status codes at all.
const { GraphQLError } = require('graphql');

if (!user) {
  throw new GraphQLError('User not found', {
    extensions: { code: 'USER_NOT_FOUND', http: { status: 404 } },
  });
}

// Response: { "errors": [{ "message": "User not found", "extensions": { "code": "USER_NOT_FOUND" } }], "data": null }
Real-world example A GraphQL API distinguishes a 'user not found' error from a generic server error by attaching a specific 'USER_NOT_FOUND' extensions code to the thrown GraphQLError, letting frontend clients programmatically handle that specific case differently from an unexpected failure.

Common follow-ups: Why does GraphQL typically return HTTP 200 even when the operation logically failed, and what's the reasoning behind that design choice?;How do you handle a scenario where one field in a query fails but others succeed, given GraphQL supports partial responses?