Javascript Debugging & Error Handling 🐞

shivams1007

Shivam Singh

Posted on October 3, 2023

Javascript Debugging & Error Handling 🐞

Hey code wranglers! 🤠 Ever felt like you're playing a never-ending game of Whack-a-Mole with JavaScript bugs? Well, today we're going to become the Indiana Jones of debugging! So, let's crack that whip and get those bugs running for cover!


1️⃣ Types of Errors in JavaScript

In the wacky world of JavaScript, not all errors are created equal. Let's meet the three musketeers of errors: Syntax, Runtime, and Logical.

Syntax Errors

These are the "drunk texts" of the JavaScript world. They make absolutely no sense and are often embarrassing.

  console.lo("Hello, World!"); // Oops! That should be console.log
Enter fullscreen mode Exit fullscreen mode

Runtime Errors

Picture yourself running in slow-motion towards success and then tripping over a rock. That's a runtime error for you.

  let x = null;
  console.log(x.name); // TypeError: Cannot read property 'name' of null
Enter fullscreen mode Exit fullscreen mode

Logical Errors

These are the "almost-but-not-quite" types. Your code runs but doesn't produce the expected output.

  let price = 10;
  let tax = 0.05;
  let total = price + tax; // Oops! Should be price + (price * tax)
Enter fullscreen mode Exit fullscreen mode

2️⃣ Console Debugging

Ah, the console, our old pal. You don't need those fancy debugging tools when you've got console.log! But wait, there's more!

Logging Levels

Who says logs have to be boring? Use console.error, console.warn, and console.info to color-code your existential coding crises.

  console.log("I am neutral.");
  console.warn("I am warning you.");
  console.error("Something went terribly wrong.");
Enter fullscreen mode Exit fullscreen mode

Console Table

Ever wanted to feel like a data scientist while debugging? Use console.table and pretend you're analyzing data for NASA.

  const heroes = [{name: 'Batman'}, {name: 'Wonder Woman'}];
  console.table(heroes);
Enter fullscreen mode Exit fullscreen mode

3️⃣ Breakpoints

Sometimes you need to put your foot down and yell, "Stop right there, JavaScript!" Let's make our code more punctuated with breakpoints.

Setting Breakpoints in Code

With debugger, you can make your code pause as if it's taking a coffee break.

  function debugThisFunction() {
    debugger;
    // code here
  }
Enter fullscreen mode Exit fullscreen mode

Breakpoint in Browser Dev Tools

You can set a breakpoint in browser dev tools and it's like pausing a Netflix show, but for your code.

  // Set breakpoint in line number in your browser
  console.log("This will be paused.");
Enter fullscreen mode Exit fullscreen mode

4️⃣ Watch Expressions

Ever stalked someone on social media? Well, this is like stalking variables. But don't worry, it's totally legal.

How to Use Watch Expressions

Add variables or expressions to the 'Watch' tab in your browser dev tools.

  // Add `x + y` in the watch tab
  const x = 10, y = 20;
Enter fullscreen mode Exit fullscreen mode

5️⃣ Error Handling 101: try, catch, finally

You can't avoid errors, but you can handle them with grace, like a cat landing on its feet.

The Try Block

Use a try block to test a block of code for errors.

  try {
    riskyFunction();
  }
Enter fullscreen mode Exit fullscreen mode

Catch and Finally

Here, catch is your superhero that saves the day when try stumbles. And finally is like your mom, telling you to clean up, whether you made a mess or not.

  try {
    riskyFunction();
  } catch(e) {
    console.error(e);
  } finally {
    console.log("I'll run no matter what.");
  }
Enter fullscreen mode Exit fullscreen mode

6️⃣ Custom Error Classes

Why settle for generic errors when you can have artisanal, handcrafted errors?

  class ValidationError extends Error {
    constructor(message) {
      super(message);
      this.name = "ValidationError";
    }
  }
Enter fullscreen mode Exit fullscreen mode

7️⃣ Stack Traces: Navigating The Error Maze 🌽

Who needs breadcrumbs when you've got a stack trace? The next time you're lost in an error, follow the stack trace back to sanity.

Reading The Stack

Stack traces point out where your code went to take a detour to la-la land. They're the "X marks the spot" on your treasure map of bugs.

function whoCalledMe() {
  console.trace();
}

function callTheFunction() {
  whoCalledMe();
}

callTheFunction();
Enter fullscreen mode Exit fullscreen mode

Deciphering Call Stacks

Sometimes call stacks look like ancient hieroglyphics. Learn to read them like Indiana Jones would!

// This would show you how the functions are being called and from where
Enter fullscreen mode Exit fullscreen mode

8️⃣ Debugging Asynchronous Code: The Future is Now (Or Maybe Later) ⏳

Asynchronous code is like that flaky friend who promises to show up but you're not sure when. Here's how to make sense of async madness.

Debugging Promises

Promises are the millennials of JavaScript: full of potential but also prone to rejection. Here's how to catch them when they fall.

const riskyPromise = new Promise((resolve, reject) => {
  // some code
  reject(new Error("Oopsie!"));
});

riskyPromise.catch(e => console.error(`Caught an error: ${e}`));
Enter fullscreen mode Exit fullscreen mode

Debugging Async/Await

Async/Await makes asynchronous code look neat but debugging it can be trickier than explaining why cats hate water.

async function riskyBusiness() {
  try {
    await someAsyncOperation();
  } catch (e) {
    console.error("Caught an async error", e);
  }
}
Enter fullscreen mode Exit fullscreen mode

Phew! Debugging and error handling are like the gym workouts of coding—no one looks forward to them, but boy, do they make you stronger! 💪

Conclusion

Congratulations, you've reached the end of this bug safari! 🎉 You're now armed with the tools and tricks to debug like a pro—or at least, like someone who doesn't resort to ritualistic dancing to make the code work.

If you've got any debugging war stories or tips to share, drop them in the comments below. Remember, the first step to recovery is admitting you have a debugging problem. 😂

Happy Debugging, Folks! 🐞

💖 💪 🙅 🚩
shivams1007
Shivam Singh

Posted on October 3, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related