Errors
GraphQL handles errors differently from REST. A REST API usually answers a failed request with a status code like 404 or 500. A GraphQL response can be partly successful: some fields have data, others failed, and the response contains both data and an errors list explaining what went wrong and where.
The shape of an error
When a resolver throws, graphql-js catches the exception, sets that field to null and adds an entry to errors:
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
type Weather { city: String!, celsius: Float }
type Query { weather(city: String!): Weather, uptime: Int }
`);
const rootValue = {
uptime: 99,
weather: ({ city }) => ({
city,
celsius: () => {
if (city === 'Atlantis') throw new Error(`No sensor data for ${city}`);
return 18.5;
},
}),
};
const result = await graphql({
schema,
rootValue,
source: `{
uptime
here: weather(city: "Lyon") { city celsius }
there: weather(city: "Atlantis") { city celsius }
}`,
});
console.log(JSON.stringify(result, null, 2));{
"errors": [
{
"message": "No sensor data for Atlantis",
"locations": [
{
"line": 4,
"column": 45
}
],
"path": [
"there",
"celsius"
]
}
],
"data": {
"uptime": 99,
"here": {
"city": "Lyon",
"celsius": 18.5
},
"there": {
"city": "Atlantis",
"celsius": null
}
}
}
Each error has:
| Key | Meaning |
|---|---|
message |
human-readable description (required) |
locations |
line/column in the query where the failing field is |
path |
the response path to the field: ["there", "celsius"] |
extensions |
optional extra data, such as an error code |
The rest of the query (uptime, here, there.city) succeeded. Clients can show what they have and degrade gracefully.
Request errors vs field errors
| Kind | When | Result |
|---|---|---|
| Request error | syntax error, validation error, bad variables | errors only, no data key |
| Field error | a resolver throws, or a value can't be serialized | data with nulls + errors |
Over HTTP, servers commonly return status 200 for field errors (the request itself worked) and 400 for request errors.
Error codes with extensions
Messages are for humans; programs need something stable to branch on. Throw a GraphQLError with extensions to attach a machine-readable code:
import { graphql, buildSchema, GraphQLError } from 'graphql';
const schema = buildSchema(`
type Query { order(id: ID!): String }
`);
const orders = { '1': 'Order #1: 2 items' };
const rootValue = {
order: ({ id }, context) => {
if (!context.user) {
throw new GraphQLError('You must be logged in.', { extensions: { code: 'UNAUTHENTICATED' } });
}
if (!orders[id]) {
throw new GraphQLError(`Order ${id} not found.`, {
extensions: { code: 'NOT_FOUND', argument: 'id' },
});
}
return orders[id];
},
};
for (const [id, user] of [['1', null], ['9', 'ana'], ['1', 'ana']]) {
const result = await graphql({
schema, rootValue, contextValue: { user },
source: 'query O($id: ID!) { order(id: $id) }', variableValues: { id },
});
const error = result.errors?.[0];
console.log(error ? `${error.extensions.code}: ${error.message}` : result.data.order);
}UNAUTHENTICATED: You must be logged in.
NOT_FOUND: Order 9 not found.
Order #1: 2 items
Common codes (used by Apollo Server and others): UNAUTHENTICATED, FORBIDDEN, BAD_USER_INPUT, NOT_FOUND, INTERNAL_SERVER_ERROR.
Don't leak internals
An unexpected exception (a database driver error, a TypeError) may contain table names, SQL or file paths. Production servers mask such errors: they log the original and send a generic message. You can do this by post-processing result.errors:
import { graphql, buildSchema, GraphQLError } from 'graphql';
const schema = buildSchema(`type Query { report: String, profile: String }`);
const rootValue = {
report: () => {
throw new Error('connect ECONNREFUSED 10.0.3.7:5432 (db=finance_prod)');
},
profile: () => {
throw new GraphQLError('Profile is private.', { extensions: { code: 'FORBIDDEN' } });
},
};
const serverLog = [];
function maskErrors(result) {
if (!result.errors) return result;
const errors = result.errors.map((error) => {
// Errors we threw on purpose are safe to show.
if (error.originalError instanceof GraphQLError || !error.originalError) return error.toJSON();
serverLog.push(error.originalError.message);
return { message: 'Internal server error', path: error.path, extensions: { code: 'INTERNAL_SERVER_ERROR' } };
});
return { ...result, errors };
}
const result = maskErrors(await graphql({ schema, rootValue, source: '{ report profile }' }));
console.log(JSON.stringify(result.errors.map((e) => [e.path[0], e.message, e.extensions.code])));
console.log('logged for developers:', serverLog);[["report","Internal server error","INTERNAL_SERVER_ERROR"],["profile","Profile is private.","FORBIDDEN"]]
logged for developers: [ 'connect ECONNREFUSED 10.0.3.7:5432 (db=finance_prod)' ]
Errors and non-null fields
Remember null propagation: if a non-null field fails, its null bubbles up to the nearest nullable parent. The error's path still points at the field that actually failed:
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
type Profile { name: String!, avatar: String! }
type Query { profile: Profile, version: String }
`);
const rootValue = {
version: '1.4.0',
profile: {
name: 'Kai',
avatar: () => { throw new Error('Image service timed out'); },
},
};
const result = await graphql({ schema, rootValue, source: '{ version profile { name avatar } }' });
console.log(JSON.stringify(result.data));
console.log(JSON.stringify(result.errors[0].path), result.errors[0].message);{"version":"1.4.0","profile":null}
["profile","avatar"] Image service timed out
profile.name was fine, but because avatar is String!, the whole profile became null. This is a strong argument for keeping fields that depend on unreliable services nullable.
Expected errors as data
Top-level errors are best for unexpected problems. For outcomes your UI must handle (wrong password, sold out, validation messages per form field) many teams model them in the schema, for example with a union Result = Success | ValidationError (see the Unions lesson) or a payload type with a userErrors: [UserError!]! field. Clients can then select them like any other data.
Test yourself
A resolver throws for one field. What does the response contain?
- Only an
errorslist datawith that field set to null, plus anerrorsentry- HTTP 500 and no body
datawith the error message as the field value
Where should a machine-readable error code go?
- In the
message - In
extensions, e.g.extensions.code - In
path - In the HTTP URL
A query has a syntax error. Does the response have a data key?
- Yes, with all fields null
- No, request errors produce only
errors - Yes, empty object
- It depends on the resolvers