Error Masking in GraphQL: What It Is and How It Works
GraphQL means hiding detailed error information from clients and sending only generic error messages. This helps protect sensitive server details and improves security by preventing clients from seeing internal error data.How It Works
Error masking in GraphQL works by intercepting errors that happen during query execution and replacing detailed error messages with simpler, less revealing ones. Imagine you are a shop owner and a customer asks why a product is unavailable. Instead of telling them exactly what went wrong in your supply chain, you just say "Sorry, this product is not available right now." This keeps your internal problems private.
In GraphQL, the server can catch errors and decide what to show the client. Instead of sending full error stacks or database details, it sends a masked message like "Internal server error." This prevents exposing sensitive information that could be misused by attackers or confuse users.
Example
const { ApolloServer, gql } = require('apollo-server'); const typeDefs = gql` type Query { secretData: String } `; const resolvers = { Query: { secretData: () => { throw new Error('Database connection failed!'); }, }, }; const server = new ApolloServer({ typeDefs, resolvers, formatError: (err) => { // Mask the error message return new Error('Internal server error'); }, }); server.listen().then(({ url }) => { console.log(`Server ready at ${url}`); });
When to Use
Error masking is useful when you want to protect your server's internal details from clients, especially in production environments. It helps prevent attackers from learning about your system's weaknesses by hiding stack traces, database errors, or sensitive info.
Use error masking when your API is public or exposed to many users, and you want to keep error messages simple and secure. However, during development, you might want to see full errors to fix bugs faster.
Key Points
- Error masking hides detailed error info from clients.
- It improves security by preventing sensitive data leaks.
- GraphQL servers can customize error messages using
formatErroror similar hooks. - Use masking in production, but show full errors in development.