logo

Error Handling

Patterns for catching and propagating errors, and how runtime errors are surfaced.

Short explanation

Use try/catch for synchronous code and catch/try with Promises or async/await for async code. Proper error propagation and logging are essential for maintainability.

Syntax example

try {
  risky();
} catch (err) {
  console.error('Failed', err);
}

async function run() {
  try {
    await doAsync();
  } catch (err) {
    console.error(err);
  }
}

How JS handles it internally

Thrown exceptions unwind the call stack until a try/catch handles them. For async code, rejected Promises propagate to their nearest handler; unhandled rejections may become process-level errors in Node.

FAQ

Q: Should I catch every error?

A: Catch where you can handle or meaningfully log/recover. Let higher-level handlers decide when to surface failures.