Learn JavaScript Β· 14/15

Error Handling and Debugging: Keeping Your Code Reliable

7 min read

Error Handling and Debugging: Keeping Your Code Reliable πŸ›

Welcome, brave coder, to the essential guide on keeping your JavaScript code from spiraling into a chaotic mess. Let's be honest, errors are like uninvited guests at a party; they show up unexpectedly and can really ruin the fun. But fear not! This guide will equip you with the tools and techniques to handle these pesky gatecrashers with grace and efficiency.


1. Try, Catch, and Finally: Handling Runtime Errors πŸ›‘οΈ

The Problem: You've written a brilliant piece of code, but sometimes, things go wrong while it's running. This could be due to a variety of reasons like invalid user input, a network error, or trying to use a variable that doesn't exist. These are called runtime errors, and they can crash your script.

The Solution: JavaScript provides a powerful construct called the try...catch...finally block to gracefully handle these runtime errors.

Imagine you're a bomb disposal expert. You try to defuse the bomb (your code). If something goes wrong, you catch the explosion (the error) in a blast-proof container so it doesn't cause any damage. And finally, whether you succeed or not, you always clean up your tools.

Here's how it looks in code:

javascript
try {
  // Code that might throw an error
  let result = riskyOperation();
  console.log(result);
} catch (error) {
  // Code to handle the error
  console.error("Oops, something went wrong:", error.message);
} finally {
  // Code that will always run, error or not
  console.log("Cleaning up resources.");
}

Breakdown of the Blocks:

  • try: This is where you place the code that you suspect might cause an error. If an error occurs within this block, the execution of the block is stopped, and the control is passed to the catch block.
  • catch: This block is executed only if an error occurs in the try block. The error object passed to it contains information about the error, such as its name and a descriptive message.
  • finally: This block is optional, but it's super useful. The code inside finally will always execute, regardless of whether an error occurred or not. It's the perfect place for cleanup tasks, like closing a file or a network connection.

A Real-World Scenario: Let's say we're parsing a JSON string that might be malformed.

javascript
let jsonString = '{"name": "Alice", "age": 30}'; // A valid JSON string
let malformedJsonString = '{"name": "Bob", "age": }'; // An invalid JSON string

function parseJson(json) {
  try {
    let user = JSON.parse(json);
    console.log("Successfully parsed:", user);
  } catch (error) {
    console.error("Invalid JSON string! Here's the error:", error.name, error.message);
  } finally {
    console.log("Attempted to parse JSON.");
  }
}

parseJson(jsonString);
parseJson(malformedJsonString);

Interesting Fact: The try...catch block only works for runtime errors. It won't catch syntax errors (like a missing parenthesis). Your code needs to be valid JavaScript for try...catch to do its job.


2. Throwing Custom Errors for Better Validation 🎯

The Problem: Sometimes, the built-in JavaScript errors aren't specific enough for your application's logic. For example, if a user enters an age that's a negative number, that's not a SyntaxError or a TypeError, but it's definitely an error in the context of your application.

The Solution: You can create and throw your own custom errors! This allows you to provide more meaningful and specific error messages, which is incredibly helpful for debugging and for other developers using your code.

Think of it like being a bouncer at a club. If someone underage tries to get in, you don't just say "Error." You say, "Sorry, you must be 18 or older to enter."

You can throw any expression, but it's a best practice to throw an Error object or an object that extends Error.

javascript
function checkAge(age) {
  if (age < 18) {
    throw new Error("You must be at least 18 years old.");
  }
  return "Access granted!";
}

try {
  let status = checkAge(15);
  console.log(status);
} catch (error) {
  console.error(error.message); // Outputs: You must be at least 18 years old.
}

Creating Custom Error Classes: For more complex applications, you can create your own error classes by extending the built-in Error class. This is fantastic for creating a hierarchy of errors and adding more properties to your error objects, like an error code.

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

function validateUsername(username) {
  if (username.length < 3) {
    throw new ValidationError("Username must be at least 3 characters long.");
  }
  return true;
}

try {
  validateUsername("Jo");
} catch (error) {
  if (error instanceof ValidationError) {
    console.error("Validation failed:", error.message);
  } else {
    console.error("An unexpected error occurred:", error);
  }
}

Industry Practice: Always throw Error objects or instances of classes that extend Error. Throwing a simple string is possible but is considered bad practice because you lose the valuable stack property that helps in tracing where the error occurred.


3. Mastering Browser DevTools: Breakpoints and Stepping πŸ•΅οΈβ€β™€οΈ

The Problem: Sometimes, console.log() just doesn't cut it. You need to pause your code in the middle of its execution and inspect everything – the values of variables, the call stack, and the overall state of your application.

The Solution: The debugger in your browser's Developer Tools is your new best friend. It allows you to set breakpoints, which are points in your code where the execution will pause.

Imagine you're a detective investigating a crime scene. You don't just look at the final outcome; you want to go back in time and see the events unfold step-by-step. Breakpoints let you do just that with your code.

Getting Started:

  1. Open DevTools: Right-click anywhere on a webpage and select "Inspect," or press F12 (Cmd + Option + I on Mac).
  2. Go to the Sources Tab: This tab shows you all the files loaded for the webpage.
  3. Set a Breakpoint: Find your JavaScript file and click on the line number where you want to pause the execution. A blue marker will appear, indicating a breakpoint.

Now, when you run your code (e.g., by clicking a button that triggers the function), the execution will halt at the breakpoint.

Stepping Through Your Code:

Once paused, you have a few options to control the flow of execution:

  • Resume execution (F8): Continue running the code until the next breakpoint.
  • Step over next function call (F10): Execute the current line of code and move to the next one. If the current line is a function call, it will execute the entire function without stepping into it.
  • Step into next function call (F11): If the current line is a function call, this will move the debugger into that function, allowing you to debug it line by line.
  • Step out of current function (Shift + F11): If you're inside a function, this will execute the rest of the function and then pause at the line where the function was called.

Inspecting Variables:

While paused, you can hover over variables in your code to see their current values. You can also use the "Scope" and "Watch" panels in the debugger to get a more detailed view of local and global variables and even watch specific expressions.


4. Advanced Console Methods: table, warn, and group πŸ“œ

The Problem: Your console.log() statements are getting out of hand. It's a jumbled mess of strings and objects, making it hard to find the information you need.

The Solution: The console object is more than just log(). It has a whole suite of methods to make your debugging output more organized and readable.

console.table()

This is a game-changer for displaying arrays of objects or just objects in a clean, tabular format.

javascript
const users = [
  { id: 1, name: "Alice", email: "[email protected]" },
  { id: 2, name: "Bob", email: "[email protected]" },
  { id: 3, name: "Charlie", email: "[email protected]" },
];

console.table(users);

console.warn()

This displays a warning message, often with a yellow background, to indicate potential issues that aren't necessarily errors.

javascript
console.warn("This feature is deprecated and will be removed in a future version.");

console.group() and console.groupEnd()

These methods allow you to group related console messages together, which can be collapsed and expanded. This is incredibly useful for organizing logs from different parts of your application.

javascript
console.group("User Authentication");
console.log("Attempting to log in user...");
console.warn("Password is weak.");
console.group("User Details");
console.log("Name: John Doe");
console.log("ID: 123");
console.groupEnd();
console.log("Login successful.");
console.groupEnd();

By mastering these error handling and debugging techniques, you'll write more reliable code, fix bugs faster, and generally be a happier and more productive developer. Happy coding! 😊


πŸ“š Further Reading and References

Challenge

Challenge Instructions

Your task is to implement a robust user profile processing system in JavaScript that handles data validation and potential errors gracefully.

  1. Create a Custom Error Type:
    Define a custom error class named ValidationError that extends the built-in Error class. The constructor should accept a message and set the error's name property to 'ValidationError'.

  2. Implement a Validation Function:
    Create a function named validateProfile(user) that takes a user object. This function must throw a ValidationError with a descriptive message if any of the following conditions are met:

    • The user object is missing any of the required properties: name, age, or email.
    • The age property is not a number or is less than or equal to 0.
    • The email property is not a string or does not contain the @ symbol.
  3. Create the Main Processing Function:
    Develop a function named processUserProfile(user). This function must use a try...catch...finally block to manage the validation process.

    • Inside the try block, call the validateProfile(user) function. If validation is successful, use console.log() to output the string: "User profile is valid.".
    • The catch block must catch any errors. Inside it, use console.warn() to output the message property of the caught error.
    • The finally block must always execute and use console.log() to output the string: "Profile processing complete.".

Expected result

Your final code should meet the following criteria:

  • A ValidationError class is correctly defined and extends Error.
  • The validateProfile function correctly throws a ValidationError for:
    • Missing name, age, or email properties.
    • An age that is non-numeric or not positive.
    • An email string that lacks an @ symbol.
  • The processUserProfile function contains a try...catch...finally block.
  • The try block calls validateProfile(user) and logs "User profile is valid." on success.
  • The catch block logs the error's message to the console using console.warn().
  • The finally block logs "Profile processing complete." to the console.
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.