Error Handling in JavaScript Interviews
JS جاوااسکریپت

Error Handling in JavaScript Interviews

try/catch/finally, custom errors, unhandled rejections, and defensive async patterns.

BugCast Admin··۵ دقیقه مطالعه

Robust error handling separates production-ready developers from tutorial-level code. Interviews cover sync errors, Promise rejections, and global handlers.

Common Interview Questions

Q: Does try/catch catch async errors in async functions?

Answer: Yes, if you await inside try/catch — rejected Promises become catchable exceptions. Without await, a .then rejection bypasses surrounding try/catch.


async function load() {
  try {
    const data = await fetch("/api");
    if (!data.ok) throw new Error("HTTP " + data.status);
  } catch (err) {
    console.error(err);
  }
}

Q: What is the difference between Error and thrown strings?

Answer: Always throw Error objects (or subclasses) for stack traces and consistent handling. Throwing strings loses debugging context.

Q: Custom error classes?

Answer: Subclass Error, set name, and attach metadata. Use instanceof or error codes for branching in API layers.


class ValidationError extends Error {
  constructor(message, field) {
    super(message);
    this.name = "ValidationError";
    this.field = field;
  }
}

Q: Unhandled promise rejection?

Answer: Node and browsers emit unhandledrejection events. Always .catch() or try/catch awaited promises. In Node 15+, unhandled rejections can crash the process.

Key Points for Interviews

  • Prefer Error objects with meaningful messages

  • Async errors need await inside try/catch

  • finally runs regardless of success or failure

  • Distinguish operational vs programmer errors in APIs

  • Global handlers are last resort, not primary strategy

#errors#async#interview

مطالب مرتبط