Error Handling
try/catch in async code, process-level handlers, and operational vs programmer errors
Skills taught: node.try-catch-async, node.error-types, node.process-error-handlers, node.custom-errors
Async error handling patterns
// ── Custom error classes ──
class AppError extends Error {
constructor(message, statusCode = 500, code = 'INTERNAL_ERROR') {
super(message);
this.name = this.constructor.name;
this.statusCode = statusCode;
this.code = code;
this.isOperational = true; // expected error, not a bug
Error.captureStackTrace(this, this.constructor);
}
}
class NotFoundError extends AppError { constructor(msg) { super(msg, 404, 'NOT_FOUND'); } }
class ValidationError extends AppError { constructor(msg) { super(msg, 422, 'VALIDATION_ERROR'); } }
class UnauthorizedError extends AppError { constructor(msg) { super(msg, 401, 'UNAUTHORIZED'); } }
// ── Async/await error handling ──
async function getUserById(id) {
if (typeof id !== 'number') throw new ValidationError('id must be a number');
if (id <= 0) throw new ValidationError('id must be positive');
if (id > 100) throw new NotFoundError(`User ${id} not found`);
return { id, name: 'Alice', email: 'alice@example.com' };
}
async function handleGetUser(id) {
try {
const user = await getUserById(id);
console.log('User found:', user);
} catch (err) {
if (err.isOperational) {
// Expected error — handle gracefully
console.error(`[${err.statusCode}] ${err.name}: ${err.message}`);
} else {
// Programmer error — let it propagate (or crash)
throw err;
}
}
}
// ── process-level handlers ──
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise);
console.error('Reason:', reason);
// In production: log + graceful shutdown
process.exit(1);
});
process.on('uncaughtException', (err, origin) => {
console.error('Uncaught Exception:', err.message);
console.error('Origin:', origin);
process.exit(1);
});
// Usage
(async () => {
await handleGetUser(1); // success
await handleGetUser(-1); // ValidationError
await handleGetUser(999); // NotFoundError
})();
const express = require('express');
const app = express();
// Async handler wrapper — catches rejected promises and forwards to next(err)
const asyncHandler = fn => (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
// Route with async handler
app.get('/users/:id', asyncHandler(async (req, res) => {
const id = parseInt(req.params.id, 10);
if (isNaN(id)) throw new ValidationError('id must be a number');
const user = await getUserById(id);
res.json(user);
}));
// Error middleware — must have 4 parameters
app.use((err, req, res, next) => {
console.error(err); // log for observability
if (err.isOperational) {
// Known, expected error — send structured response
return res.status(err.statusCode).json({
error: {
code: err.code,
message: err.message,
}
});
}
// Unknown error — don't expose internals
res.status(500).json({
error: { code: 'INTERNAL_ERROR', message: 'Something went wrong' }
});
});
Tip: Never write an empty catch block: `catch (err) {}`. If you don't handle an error, at least log it with `console.error(err)`. Silent error swallowing is one of the hardest bugs to debug.
Frequently Asked Questions
My async function throws an error but nothing happens — why?
You likely called the async function without await and without .catch(). The promise rejects silently. Always do one of: (1) `await asyncFn()` inside a try/catch, (2) `asyncFn().catch(handleError)`, or (3) listen to `process.on('unhandledRejection', ...)` as a safety net. In Node.js 15+, unhandled rejections crash the process — so 'nothing happens' in older Node versions but crashes in newer ones.