Simulator
Error Handling Playground
Six classic ways Node.js programs blow up. Run each one, read the real crash output, then expand the fix to see the pattern that prevents it.
Synchronous throw
try/catchSynchronous code that throws — like parsing bad JSON — crashes the whole process unless something catches it.
const raw = '{ invalid json }';
const config = JSON.parse(raw); // 💥 throws synchronously
console.log('port:', config.port); // never runsError-first callbacks
callbacksClassic Node APIs pass errors as the callback's first argument. Ignore it, and you'll crash on undefined data instead of handling the real problem.
const fs = require('fs');
fs.readFile('/missing.txt', 'utf8', (err, data) => {
// 🐛 err is never checked!
console.log('length:', data.length);
});Unhandled promise rejection
promisesA rejected promise with no .catch() anywhere is fatal in modern Node — the process exits, just like an uncaught throw.
function fetchUser(id) {
return Promise.reject(new Error('User ' + id + ' not found'));
}
fetchUser(42).then((user) => {
console.log(user.name);
}); // 🐛 no .catch() anywhereasync/await without try/catch
async/awaitawait turns a rejection back into a throw. If nothing in the async call chain catches it, you're back to an unhandled rejection.
async function loadDashboard() {
const stats = await fetchStats(); // rejects: DB timeout
console.log('users online:', stats.online);
}
loadDashboard(); // 🐛 rejection escapes the async functionCustom Error subclass
AppErrorThrowing bare Error objects means every failure looks identical. A custom subclass carries structured context — like an HTTP status code.
class AppError extends Error {
constructor(message, statusCode) {
super(message);
this.name = 'AppError';
this.statusCode = statusCode;
Error.captureStackTrace(this, this.constructor);
}
}
throw new AppError('User not found', 404);Express error middleware
ExpressIn Express 4, an error thrown in an async route never reaches Express — the request just hangs until the client gives up.
app.get('/users/:id', async (req, res) => {
const user = await db.findUser(req.params.id);
// 🐛 rejects → Express 4 never hears about it
res.json(user);
});
// client: curl http://localhost:3000/users/999