Custom error extensions in GraphQL - Time & Space Complexity
When using custom error extensions in GraphQL, it's important to understand how the process of adding extra error details affects performance.
We want to know how the time to handle errors grows as the number of errors or the size of error details increases.
Analyze the time complexity of this GraphQL error handling snippet.
type Query {
getUser(id: ID!): User
}
type User {
id: ID!
name: String
}
// Resolver example
function getUserResolver(parent, args) {
try {
// fetch user logic
} catch (error) {
throw new GraphQLError("User not found", {
extensions: { code: "USER_NOT_FOUND", timestamp: Date.now() }
});
}
}
This code adds custom extensions to errors thrown during query resolution.
Look for repeated actions that affect time.
- Primary operation: Adding custom extensions to each error object.
- How many times: Once per error thrown during query execution.
As the number of errors increases, the time to add extensions grows linearly.
| Input Size (number of errors) | Approx. Operations |
|---|---|
| 1 | 1 operation to add extensions |
| 10 | 10 operations to add extensions |
| 100 | 100 operations to add extensions |
Pattern observation: The work grows directly with the number of errors.
Time Complexity: O(n)
This means the time to add custom error extensions grows in a straight line with the number of errors.
[X] Wrong: "Adding custom extensions to errors is instant and does not affect performance."
[OK] Correct: Each error requires extra processing to add extensions, so more errors mean more work and longer time.
Understanding how error handling scales helps you write efficient GraphQL APIs and shows you can think about performance beyond just query logic.
What if we added nested objects or large data inside the error extensions? How would the time complexity change?