Skip to content

Error Handling

try/catch/finally, custom error types, and graceful recovery for sync and async failures.

What you'll learn

  • try/catch/finally for synchronous error handling
  • Throwing and catching Error objects
  • Creating custom error subclasses for specific cases
  • Handling async errors with try/catch around await
  • Global error handlers and unhandled rejection listeners

Concept

try / catch / finally

try wraps code that might throw. catch receives the thrown value if an error occurs. finally runs whether or not an error was thrown, making it the place for cleanup (closing files, releasing locks). In modern JavaScript, catch can omit the binding (catch { }) when you do not need the error object. Only throw Error objects — throwing strings or numbers loses the stack trace.

The Error Object

The built-in Error has a message, a name, and a stack property (non-standard but widely supported). JavaScript provides subclasses: TypeError, RangeError, SyntaxError, ReferenceError, URIError, and EvalError. Catching by type lets you handle different failures differently — check instanceof in the catch block.

Custom Errors

For application-specific failures, extend Error to create a named subclass. Set this.name and call super(message) in the constructor. Custom errors make it easy to distinguish a "not found" from a "validation failure" at the catch site, and they carry extra fields (like a status code) that generic errors do not.

Async Error Handling

With async/await, errors are caught with the same try/catch — await throws when a promise rejects. For promise chains, use .catch(). Always handle rejections: an unhandled rejection can crash Node.js (since v15) and logs warnings in browsers. Listen with process.on('unhandledRejection') in Node or window.addEventListener('unhandledrejection') in browsers.

Global Handlers

Some errors escape every try/catch — errors in event listeners, timers, or top-level code. Register global handlers as a safety net to log and report them, but do not use them as your primary strategy. The goal is to handle errors as close to their source as possible, where you have the context to recover meaningfully.

Example

              // Custom error subclass with extra context
class ValidationError extends Error {
  constructor(field, message) {
    super(message);
    this.name = "ValidationError";
    this.field = field;
  }
}

class NotFoundError extends Error {
  constructor(resource) {
    super(`${resource} not found`);
    this.name = "NotFoundError";
  }
}

// Throwing and catching by type
function findUser(id) {
  if (typeof id !== "number") throw new ValidationError("id", "must be a number");
  if (id < 1) throw new ValidationError("id", "must be positive");
  if (id > 100) throw new NotFoundError("User");
  return { id, name: "Ada" };
}

try {
  const user = findUser(999);
  console.log(user);
} catch (e) {
  if (e instanceof ValidationError) {
    console.log(`Validation failed on '${e.field}': ${e.message}`);
  } else if (e instanceof NotFoundError) {
    console.log("Not found:", e.message);
  } else {
    throw e; // re-throw unknown errors
  }
} finally {
  console.log("lookup complete");
}

// Async error handling with try/catch
async function safeFetch(url) {
  try {
    const res = await fetch(url);
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    return await res.json();
  } catch (e) {
    console.error("Fetch failed:", e.name, e.message);
    return null;
  }
}

// Global safety net (browser)
window.addEventListener("unhandledrejection", (e) => {
  console.error("Unhandled rejection:", e.reason);
});
            

Shows custom error subclasses with extra fields, throwing and catching by type with instanceof, re-throwing unknown errors, finally for cleanup, async error handling, and a global unhandledrejection listener.

Try it

Common mistakes

The mistake

Throwing strings or numbers instead of Error objects

The fix

Always throw new Error('message'). Strings and numbers have no stack trace and cannot be caught by type with instanceof. Use custom Error subclasses for specific cases.

The mistake

Catching errors too broadly and hiding real bugs

The fix

Do not wrap entire functions in a try/catch that silently returns null. Catch specific error types, handle what you expect, and re-throw unknown errors so real bugs surface instead of being swallowed.

Related Cheatsheets

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors