JavaScript Tutorial

Error Handling

try/catch, custom errors, Error types, and global error handlers

What are JavaScript Errors?

In JavaScript, an error is a special object that indicates that something went wrong during the execution of your program. If not "caught" or "handled", it will cause the program to crash. Errors are not your enemy—they are a guide to identifying and fixing bugs!
javascript
// A simple error (ReferenceError!)
// console.log(x);

// Handle it!
try {
  console.log(x);
} catch (err) {
  console.log("Error caught: x is not defined!");
}
// 1. "Error caught: x is not defined!" (Program continues!)

Handling Errors with try/catch/finally

  • try: Block of code you want to "monitor" for errors.
  • catch(err): Block that runs ONLY if an error occurs.
  • finally: Block that runs no matter what, whether an error occurred or not. Use this for cleanup logic (like hiding a loading spinner).
javascript
try {
  // Logic that might fail
  const user = await fetchUser();
} catch (error) {
  // Handle the error!
  console.error("Fetch failed:", error.message);
} finally {
  console.log("Process complete.");
}

Throwing Errors: throw

You can explicitly trigger an error because a certain business condition isn't met.
javascript
const setAge = (age) => {
  if (age < 0) {
      // Trigger an error manually!
      throw new Error("Age cannot be negative!");
  }
  return age;
};

try {
  setAge(-5);
} catch (e) {
  console.error(e.message);
}

Creating Custom Errors

For large-scale projects, it's often more descriptive to create your own Error types.
javascript
// Customize by inheriting from the base 'Error' class
class DatabaseError extends Error {
  constructor(message) {
    super(message);
    this.name = "DatabaseError";
  }
}

throw new DatabaseError("Could not connect to localhost:3306");

Built-in Error Types (Most Common)

Error TypeMeaning
TypeErrorVariable is of the wrong type (e.g., null.prop)
ReferenceErrorYou used a variable that doesn't exist
SyntaxErrorTypos in your code that JS can't parse
RangeErrorValue is outside the allowed range (e.g., new Array(-1))
URIErrorError during URL encoding/decoding

Summary

TermDescription
tryMonitor for crashes
catchRecover from errors
finallyFinal cleanup logic
throwManually trigger an error
CustomCreate custom error classes
ErrorThe base object for all built-in errors
Best ForBug prevention, resilient code, input validation
AsyncAlways use try/catch with async/await!
Stack TraceThe chain of calls that led to the crash
messageThe descriptive string of the error
nameThe specific type (e.g., "TypeError")
Silent FailDon't catch an error and do NOTHING! (Always log it!)
NetworkHandling failed API responses
BrowserUse window.onerror for global error catching
Node.jsUse process.on('uncaughtException')
PolyfillNative support in all environments
DebuggingPause on exceptions in browser DevTools
LoggingSend error data to a service (like Sentry)
Re-throwYou can catch and then throw again to bubble it up
Top-LevelError handling should wrap your entire "main" logic
SecurityNever expose internal stack traces to the end-user!