GraphQL API
Error Handling
GraphQL error codes and handling
Error Handling
The GraphQL API uses standardized error codes for consistent error handling.
Error Response Format
{
"errors": [
{
"message": "Human-readable error message",
"extensions": {
"code": "ERROR_CODE",
"additionalInfo": "Optional additional context"
},
"path": ["field", "path", "to", "error"],
"locations": [{ "line": 2, "column": 3 }]
}
],
"data": null
}Common Error Codes
| Code | Description | HTTP Equivalent |
|---|---|---|
UNAUTHENTICATED | Authentication required but not provided | 401 |
FORBIDDEN | User lacks permission for the requested operation | 403 |
NOT_FOUND | Requested resource does not exist | 404 |
INVALID_DATA | Request contains invalid data | 400 |
RATE_LIMIT_EXCEEDED | Too many requests in time window | 429 |
DEPTH_LIMIT_EXCEEDED | Query nesting exceeds allowed depth | 400 |
COMPLEXITY_LIMIT_EXCEEDED | Query complexity exceeds limit | 400 |
FIELD_LIMIT_EXCEEDED | Too many fields selected | 400 |
BATCH_LIMIT_EXCEEDED | Too many operations in batch | 400 |
QUERY_TOO_LARGE | Query string exceeds size limit | 413 |
CSRF_PROTECTION_FAILED | Missing required security header | 400 |
QUERY_TIMEOUT | Query execution exceeded time limit | 408 |
INTERNAL_SERVER_ERROR | Unexpected server error | 500 |
Handling Errors in Client Code
async function executeQuery(query, variables) {
try {
const response = await fetch('/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
'x-graphql-request': 'true',
},
body: JSON.stringify({ query, variables }),
});
const result = await response.json();
if (result.errors) {
// Handle GraphQL errors
for (const error of result.errors) {
const code = error.extensions?.code;
switch (code) {
case 'UNAUTHENTICATED':
// Redirect to login
window.location.href = '/login';
break;
case 'FORBIDDEN':
// Show permission error
showError('You do not have permission for this action');
break;
case 'RATE_LIMIT_EXCEEDED':
const retryAfter = error.extensions.retryAfter;
showError(`Rate limit exceeded. Please retry in ${retryAfter} seconds`);
break;
case 'NOT_FOUND':
showError('The requested resource was not found');
break;
default:
showError(error.message);
}
}
return null;
}
return result.data;
} catch (error) {
// Handle network errors
console.error('Network error:', error);
showError('Unable to connect to the server');
return null;
}
}