Skip to content

 Error Handling and Debugging

Handling Errors with try/catch

Use try/catch to handle synchronous errors.

try {
  const result = riskyFunction();
  console.log(result);
} catch (err) {
  console.error("Error:", err.message);
}

Example:

try {
  const x = y + 1; // y is not defined
} catch (err) {
  console.error("Caught error:", err.message);
}

Handling Async Errors with Promises

fetchData()
  .then((res) => {
    console.log(res);
  })
  .catch((err) => {
    console.error("Error:", err);
  });

Async/Await with try/catch

async function loadData() {
  try {
    const res = await fetchSomething();
    console.log(res);
  } catch (err) {
    console.error("Async Error:", err.message);
  }
}

Emitting and Handling Error Events

Some core modules like streams emit error events.

const fs = require("fs");
const stream = fs.createReadStream("missing.txt");

stream.on("error", (err) => {
  console.error("Stream error:", err.message);
});

Throwing Custom Errors

function divide(a, b) {
  if (b === 0) throw new Error("Cannot divide by zero");
  return a / b;
}

Global Error Handlers

Catch unhandled errors:

process.on("uncaughtException", (err) => {
  console.error("Uncaught Exception:", err);
});

For unhandled Promise rejections:

process.on("unhandledRejection", (reason) => {
  console.error("Unhandled Rejection:", reason);
});

Debugging

1. console.log

Simple and fast, use it to inspect values.

console.log("Debug here:", variable);

2. debugger Keyword

Pauses execution like a breakpoint.

function test() {
  const a = 5;
  debugger;
  const b = a + 10;
  return b;
}

Run with:

node inspect app.js

Then use n, c, repl, etc. to step through the code.

3. VS Code Debugger

  • Set breakpoints directly in the editor
  • Use launch configuration (.vscode/launch.json)
  • Run using the built-in debugger

Summary

Tool/Technique Purpose
try/catch Handle sync or async errors
.catch() Handle Promise errors
error events Handle stream/module errors
debugger Pause execution for inspection
console.log Basic output for debugging
inspect Built-in Node debugger