Unlike REST, where an error typically corresponds to a non-2xx HTTP status code, a GraphQL response almost always returns HTTP 200, with errors instead reported in a dedicated 'errors' array alongside any partial 'data' that could still be resolved -- custom error classes extending GraphQLError can attach an 'extensions' object with a machine-readable error code and additional context, letting clients distinguish error types without relying on HTTP status codes at all.
A GraphQL API distinguishes a 'user not found' error from a generic server error by attaching a specific 'USER_NOT_FOUND' extensions code to the thrown GraphQLError, letting frontend clients programmatically handle that specific case differently from an unexpected failure.
Likely follow-ups
Why does GraphQL typically return HTTP 200 even when the operation logically failed, and what's the reasoning behind that design choice?
How do you handle a scenario where one field in a query fails but others succeed, given GraphQL supports partial responses?
A validation error indicates the request itself is malformed or violates basic data constraints (a missing required field, an invalid email format) -- typically caught early, before any business logic runs, and mapped to a 400 Bad Request. A business-logic error indicates the request is well-formed but violates a domain rule (attempting to withdraw more money than an account balance, booking an already-fully-reserved time slot) -- often mapped to a 409 Conflict or 422 Unprocessable Entity, since the request syntax was valid but the requested operation can't be completed given the current state of the system.
// Validation error: malformed request
if (!amount || amount <= 0) throw new ValidationError('Amount must be positive');
// Business-logic error: well-formed request, but violates a domain rule
if (amount > account.balance) throw new InsufficientFundsError('Insufficient balance for this withdrawal');
Real-world example
A banking API returns a 400 for a withdrawal request missing the amount field entirely (a validation error caught before touching the database), but returns a 409 for a well-formed withdrawal request that exceeds the account's actual current balance (a business-logic error only detectable after checking the account's state).
Likely follow-ups
Why does separating these two error categories with different status codes help API consumers write more precise error-handling logic?
At what layer of the application should validation typically happen versus business-logic checks?
RESTful API Design with ExpressDatabases & ORMs (MongoDB/MongooseSQL/Sequelize)
Sentry (and similar tools) provide an SDK that automatically captures uncaught exceptions, unhandled rejections, and manually reported errors, sending them along with stack traces, request context, and environment details to a centralized dashboard for triage and alerting -- before sending, sensitive data (passwords, tokens, credit card numbers, personally identifiable information) should be explicitly scrubbed via the SDK's configurable 'beforeSend' hook, since error payloads can easily and accidentally include sensitive request bodies or headers.
Sentry.init({
dsn: process.env.SENTRY_DSN,
beforeSend(event) {
if (event.request?.data?.password) delete event.request.data.password;
if (event.request?.headers?.authorization) delete event.request.headers.authorization;
return event;
},
});
app.use(Sentry.Handlers.errorHandler());
Real-world example
A team configures Sentry's beforeSend hook to strip Authorization headers and password fields from every captured error event, after discovering an early integration had been inadvertently sending full request bodies (including plaintext passwords from failed login attempts) to their error-tracking dashboard.
Likely follow-ups
What other categories of data besides credentials commonly need scrubbing from error reports for compliance reasons (like GDPR)?
How does Sentry's error grouping/fingerprinting work to avoid flooding a dashboard with thousands of instances of the same underlying issue?
Synchronous code throws an Error object directly, caught by a surrounding try/catch. Traditional Node.js callback-style asynchronous functions instead follow the 'error-first callback' convention, passing an error (or null if none occurred) as the callback's first argument, since a thrown error inside an async callback executing later couldn't be caught by a try/catch wrapped around the original function call, as that call has already returned by the time the callback runs.
// Synchronous: throw and catch
function parseConfig(json) {
try { return JSON.parse(json); } catch (err) { throw new Error('Invalid config JSON'); }
}
// Asynchronous callback-style: error-first convention
fs.readFile('config.json', (err, data) => {
if (err) return console.error('Failed to read config:', err.message);
console.log(data);
});
Real-world example
A developer new to Node.js initially wrapped an fs.readFile call in a try/catch expecting to catch a file-not-found error, only to realize the callback-based API requires checking the err parameter inside the callback itself, since the try/catch around the outer call can't catch an error surfaced asynchronously.
Likely follow-ups
Why can't a try/catch around an asynchronous callback-based function call actually catch an error that occurs inside that callback?
How does this same limitation not apply to async/await-based code?
A catch-all middleware placed after all defined routes (but before the error-handling middleware) matches any request that hasn't already been handled by an earlier route, letting the application return a consistent, well-formatted 404 response rather than Express's default plain-text 'Cannot GET /some/path' message.
// After all your defined routes
app.use((req, res) => {
res.status(404).json({ error: 'Not Found', path: req.originalUrl });
});
// Error-handling middleware still goes after this
app.use((err, req, res, next) => { /* ... */ });
Real-world example
An API that previously returned Express's default plain-text 404 page adds a catch-all JSON 404 handler, ensuring every unmatched route (a typo'd endpoint, a deprecated API version) returns a consistent, machine-parseable JSON error response matching the rest of the API's error format.
Likely follow-ups
Why must this catch-all handler be placed after every other route definition to work correctly?
How would you distinguish a genuinely undefined route from a route that exists but the specific resource ID wasn't found?
Express & MiddlewareRESTful API Design with Express