All academies

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.

Simulated output — nothing here can hurt your machine. Crash freely.
1

Synchronous throw

try/catch

Synchronous code that throws — like parsing bad JSON — crashes the whole process unless something catches it.

app.js
const raw = '{ invalid json }';

const config = JSON.parse(raw); // 💥 throws synchronously
console.log('port:', config.port); // never runs
2

Error-first callbacks

callbacks

Classic 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.

app.js
const fs = require('fs');

fs.readFile('/missing.txt', 'utf8', (err, data) => {
  // 🐛 err is never checked!
  console.log('length:', data.length);
});
3

Unhandled promise rejection

promises

A rejected promise with no .catch() anywhere is fatal in modern Node — the process exits, just like an uncaught throw.

app.js
function fetchUser(id) {
  return Promise.reject(new Error('User ' + id + ' not found'));
}

fetchUser(42).then((user) => {
  console.log(user.name);
}); // 🐛 no .catch() anywhere
4

async/await without try/catch

async/await

await turns a rejection back into a throw. If nothing in the async call chain catches it, you're back to an unhandled rejection.

app.js
async function loadDashboard() {
  const stats = await fetchStats(); // rejects: DB timeout
  console.log('users online:', stats.online);
}

loadDashboard(); // 🐛 rejection escapes the async function
5

Custom Error subclass

AppError

Throwing bare Error objects means every failure looks identical. A custom subclass carries structured context — like an HTTP status code.

errors.js + app.js
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);
6

Express error middleware

Express

In Express 4, an error thrown in an async route never reaches Express — the request just hangs until the client gives up.

server.js
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