Error types and handling in GraphQL
From the GraphQL cheat sheet · Error Handling · verified Jul 2026
Error types and handling
javascript
// Apollo Server error types
const { GraphQLError } = require('graphql');
// Custom error classes
class NotFoundError extends GraphQLError {
constructor(message) {
super(message, { extensions: { code: 'NOT_FOUND' } });
}
}
class ConflictError extends GraphQLError {
constructor(message) {
super(message, { extensions: { code: 'CONFLICT' } });
}
}
// Use in resolvers
const resolvers = {
Query: {
user: async (parent, { id }, { db }) => {
const user = await db.user.findUnique({ where: { id } });
if (!user) {
throw new NotFoundError(`User with ID ${id} not found`);
}
return user;
}
},
Mutation: {
createUser: async (parent, { input }, { db }) => {
// Validation
if (!input.email.includes('@')) {
throw new GraphQLError('Invalid email format', {
extensions: { code: 'BAD_USER_INPUT', field: 'email', value: input.email }
});
}
// Check uniqueness
const existing = await db.user.findUnique({
where: { email: input.email }
});
if (existing) {
throw new ConflictError('Email already in use');
}
try {
return await db.user.create({ data: input });
} catch (error) {
// Database error
console.error('Database error:', error);
throw new GraphQLError('Failed to create user', { extensions: { code: 'DATABASE_ERROR' } });
}
}
}
};💡 GraphQL returns 200 OK even with errors
⚡ Errors in errors array, data can be partial
📌 Use custom error classes for clarity
🔥 Format errors for production