agyanadda@gmail.com

Node.js Error Handling

Asynchronous Programming 1 min read Updated Dec 3, 2026 Topic 14 of 30

Good error handling keeps your app running and makes problems easy to find.

Two kinds of errors

  • Operational errors — expected problems: invalid input, file not found, database down. Handle them and return a clear message.
  • Programmer errors — bugs: undefined is not a function. Fix the code; often the safest action is to log and restart.

Tools

  • try / catch around await
  • .catch() on promise chains
  • throw new Error('message')
  • Custom error classes — class NotFoundError extends Error with a statusCode
  • error.cause — keep the original error: new Error('Save failed', { cause: err })

Last line of defence

  • process.on('unhandledRejection', ...) — a promise rejected with no catch
  • process.on('uncaughtException', ...) — a thrown error nobody caught

Log the error, close the server cleanly, and exit with process.exit(1). A process manager (PM2, Docker, systemd) restarts the app.

Never show stack traces to users in production — log them instead.

Example

Example — Custom errors and safe shutdown JavaScript
class AppError extends Error {
  constructor(message, statusCode = 500) {
    super(message);
    this.name = 'AppError';
    this.statusCode = statusCode;
  }
}

class NotFoundError extends AppError {
  constructor(what) { super(`${what} not found`, 404); }
}

async function getProduct(id) {
  const products = { 1: 'Pen', 2: 'Notebook' };
  if (!products[id]) throw new NotFoundError(`Product ${id}`);
  return products[id];
}

try {
  console.log(await getProduct(1));   // Pen
  console.log(await getProduct(9));
} catch (err) {
  if (err instanceof AppError) console.log(err.statusCode, err.message); // 404 Product 9 not found
  else throw err;
}

process.on('unhandledRejection', (reason) => {
  console.error('Unhandled rejection:', reason);
  process.exit(1);
});

Prints Pen, then 404 Product 9 not found. Any promise rejection that nobody handles is logged and the process exits so a process manager can restart it.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which is an operational error?

Exercise 2 True / False

Showing full stack traces to users in production is a good idea.

Exercise 3 Fill in the Blank

Create custom errors by extending the built-in ___ class.

Frequently Asked Questions

No. After an uncaught exception the app may be in a broken state. Log the error, finish or close what you can, exit, and let PM2, Docker or systemd restart a clean process.