Everything, Everywhere
Verified Specification | Standardized Formulas | Instant Precision
Secure & Private (Zero Data Retention) Free Access • No Sign-Up

Error Handling

Errors happen in every application. Try/catch blocks allow you to intercept errors gracefully without crashing the whole application.

Try It Yourself

      
📋 Copy Custom Error Class & Error Chaining Snippet
// Custom Error Class with Inheritance & Cause
class NetworkError extends Error {
  constructor(message, options) {
    super(message, options);
    this.name = "NetworkError";
  }
}

try {
  throw new NetworkError("Failed to fetch user", { cause: "Timeout" });
} catch (err) {
  if (err instanceof NetworkError) {
    console.error(`[${err.name}]`, err.message, "Root cause:", err.cause);
  }
}

⚠️ 5 Fatal Traps & JavaScript Pitfalls

Trap #1: Throwing Non-Error Literals (throw "error")
Throwing raw strings or numbers (throw "Something went wrong") lacks a stack trace, making debugging production failures virtually impossible. Always throw new Error().
Trap #2: Swallowing Errors in Empty Catch Blocks
Writing catch (e) {} silently consumes failures, hiding fatal syntax flaws and network disconnections without any log trace.
Trap #3: Return Inside finally Overriding Try/Catch
Placing a return statement inside a finally block overrides any return value or uncaught exception from try and catch!
Trap #4: Async Errors Escaping try/catch Without await
Omitting await in try { asyncFunc(); } catch (e) {} allows the promise to reject asynchronously outside the try/catch boundary.
Trap #5: Masking Original Cause Without { cause: err }
Catching an error and re-throwing a generic message loses the root traceback unless wrapped with modern Error Chaining: new Error("message", { cause: err }).

💬 Frequently Asked Questions

What does the { cause: err } option do in Error constructors?
Introduced in ES2022, Error Chaining allows passing an underlying root error to { cause }, preserving the entire contextual traceback across architectural boundaries.
What is the purpose of the finally block?
The finally block executes unconditionally whether an exception was thrown, caught, or omitted, ensuring cleanup hooks (closing files, releasing locks) always run.
How do you catch unhandled promise rejections globally?
In browsers: window.addEventListener("unhandledrejection", e => { ... }). In Node.js: process.on("unhandledRejection", (reason, promise) => { ... }).
What is the difference between ReferenceError, TypeError, and SyntaxError?
ReferenceError occurs when reading an undeclared variable. TypeError occurs when an operation is performed on an incompatible type (e.g. null.f()). SyntaxError occurs when code violates JS grammar rules.
Can you omit the error variable in a catch block?
Yes, Optional Catch Binding (ES2019) allows writing try { ... } catch { ... } without specifying an unused (error) parameter.
Sponsored Utility
While You're Here
Sponsored Recommendations
Advertisement