Advanced Error Handling

  • This lesson dives into advanced strategies for handling errors effectively.
  • Introduction to Advanced Error Handling

    In real-world JavaScript applications, errors are inevitable.
    What separates a beginner from a professional developer is how errors are handled.

    Poor error handling can lead to:

    • Application crashes

    • Confusing messages

    • Bad user experience

    • Difficult debugging

    Good error handling ensures:

    • Application stability

    • Clear debugging

    • Smooth user experience

    • Professional-quality code

    In this lesson, we will cover:

    1. Error Object Properties

    2. Graceful Error Handling

    3. User-Friendly Error Messages

    Error Object Properties

    What Is an Error Object ?

    When an error occurs in JavaScript, the engine creates an Error object automatically.

    This object contains useful information about:

    • What went wrong

    • Where it went wrong

    • How the error occurred

    Creating an Error Object

    let error = new Error("Something went wrong");

    console.log(error);

    Common Error Object Properties

    JavaScript Error objects mainly contain three important properties:

    1. name

    2. message

    3. stack

    name Property

    What It Is

    The name property specifies the type of error.

    Common Error Names

    • Error

    • TypeError

    • ReferenceError

    • SyntaxError

    • RangeError

Error Name Handling Example

Catches an error and prints its type using error.name.

try {
  let x = y; // y is not defined
} catch (error) {
  console.log(error.name);
}
  • message Property

    What It Is

    The message property provides a human-readable description of the error.

Error Message Handling Example

Catches a type error and displays the error message using error.message.

try {
  let num = 5;
  num.toUpperCase();
} catch (error) {
  console.log(error.message);
}
  • stack Property

    What It Is

    The stack property contains a stack trace, showing:

    • Function call order

    • File names

    • Line numbers

    This is extremely useful for debugging.

Error Stack Trace Example

Catches an error and prints the full stack trace using error.stack.

try {
  function test() {
    throw new Error("Test error");
  }
  test();
} catch (error) {
  console.log(error.stack);
}
  • When to Use Error Properties

    Property

    Used For

    name

    Identifying error type

    message

    Displaying or logging error

    stack

    Debugging and tracing

    Graceful Error Handling

    What Is Graceful Error Handling ?

    Graceful error handling means: 

    • The application does not crash

    • Errors are handled smoothly

    • The user is not exposed to technical details

    • The system recovers or continues safely

    Bad Error Handling Example

    let data = JSON.parse("{invalid json}");

    This crashes the program.

JSON Parse Error Handling Example

Uses try-catch to handle invalid JSON parsing and show a friendly error message.

try {
  let data = JSON.parse("{invalid json}");
} catch (error) {
  console.log("Something went wrong. Please try again.");
}
  • The application continues running.

    Using finally Block

    The finally block always executes, whether an error occurs or not.

Try-Catch-Finally Flow Example

Ensures cleanup code runs after handling an error using finally.

try {
  console.log("Processing...");
  throw new Error("Failed");
} catch (error) {
  console.log("Error handled");
} finally {
  console.log("Cleanup done");
}

Error Type Checking Example

Uses instanceof to identify and handle specific error types in catch block.

try {
  let value = undefined;
  value.toString();
} catch (error) {
  if (error instanceof TypeError) {
    console.log("Type error occurred");
  } else {
    console.log("Unknown error");
  }
}

Default Value Handling Example

Uses logical OR (||) to return a default value when input is empty or falsy.

function getUsername(name) {
  return name || "Guest";
}

console.log(getUsername(""));
  • Instead of crashing, a default value is returned.

    Logging Errors Without Breaking App

Generic Error Handling Example

Uses try-catch to safely handle errors from an undefined risky function.

try {
  riskyFunction();
} catch (error) {
  console.error(error.message);
}
  • Error is logged, app keeps running.

    User-Friendly Error Messages

    Why User-Friendly Errors Are Important

    Technical error messages:

    • Confuse users

    • Look unprofessional

    • Expose internal logic

    Users need:

    • Simple language

    • Clear instructions

    • Guidance on what to do next

    Bad User Error Message

    TypeError: Cannot read properties of undefined

    This is useful for developers, not users.

    Good User-Friendly Error Message

    Something went wrong while loading data.

    Please refresh the page or try again later.

    Separating Developer and User Messages

User-Friendly Error Handling Example

Logs detailed error for developers and shows a simple message to users.

try {
  riskyFunction();
} catch (error) {
  console.error(error); // Developer log
  alert("Something went wrong. Please try again.");
}

Custom Error Throwing Example

Throws a custom error when invalid input is detected and handles it using try-catch.

function divide(a, b) {
  if (b === 0) {
    throw new Error("Division by zero is not allowed");
  }
  return a / b;
}

try {
  divide(10, 0);
} catch (error) {
  console.log(error.message);  }

Input Validation Error Example

Validates user input and throws an error if the condition is not met.

function validateAge(age) {
  if (age < 18) {
    throw new Error("You must be at least 18 years old");
  }
}

try {
  validateAge(16);
} catch (error) {
  console.log(error.message);
}
  • Best Practices for User-Friendly Errors

    • Use simple language

    • Avoid technical terms

    • Be polite and calm

    • Provide next steps

    • Do not blame the user

    Common Beginner Mistakes

    • Showing raw error messages to users

    • Ignoring errors completely

    • Using try...catch everywhere unnecessarily

    • Not logging errors for debugging

    • Throwing unclear error messages

    Professional Error Handling Strategy

    • Catch errors at the right level

    • Log detailed errors for developers

    • Show clean messages to users

    • Use fallback logic

    • Monitor and improve

    Real-World Examples

    • Login failure message

    • Network error handling

    • Invalid form input

    • API response errors

    • Payment failure handling