Skip to main content

Command Palette

Search for a command to run...

Error Handling in JavaScript

Updated
3 min read

Effective error handling is the difference between an app that crashes and burns and one that recovers with grace. Here we will be discussing about mastering try...catch flow.

What is JavaScript Errors?

In JavaScript an error is an object that represents an abnormal condition in the code. When the engine encounters something it can't handle like calling a function that doesn't exist or to parse invalid JSON, it throws an error.

Common Runtime Examples:

  • ReferenceError: Using a variable that hasn't been declared.

  • TypeError: Performing an operation on the wrong data type (e.g. null.toUpperCase() ).

  • SyntaxError: Writing code that the engine literally cannot read.


The Safety Net: try and catch

The try...catch statement allows you to "test" a block of code and "catch" any errors that occur within it, preventing the entire program from crashing.

How it Works:

  1. try: wrap the code that might fail inside this block.

  2. catch: If an error occurs, the engine stops executing the try block and jumps straight to the catch block.

try {
  let data = JSON.parse(incompleteJsonString); 
  console.log(data);
} catch (error) {
  console.error("Oops! We couldn't process that data.");
  console.log("Error message:", error.message);
}

This is graceful failure. Instead of a blank screen, the user might see a helpful message, or the app might log the error to a server and continue running other tasks.


The finally Block: The Clean-Up Crew

Sometimes, you need to run code regardless of whether an error occurred or not. This is where finally comes in. It executes after try and catch are finished, no matter what the outcomes was.

Common use case: Closing a database connection or hiding a "loading" spinner.

let isLoading = true;

try {
  fetchData(); // Imagine this fails
} catch (err) {
  handleError(err);
} finally {
  isLoading = false; // This runs whether fetchData succeeded or failed
  console.log("Cleanup complete.");
}

Taking Control: Throwing Custom Errors

You don't have to wait for JavaScript to find a problem. You can define your own rules using the throw keyword. This is especially useful for validation.

function setAge(age) {
  if (age < 0) {
    throw new Error("Age cannot be negative!");
  }
  return `Age set to ${age}`;
}

try {
  setAge(-5);
} catch (e) {
  console.warn(e.name + ": " + e.message); // Error: Age cannot be negative!
}

By throwing custom errors, you make your code more predictable and easier for other developers (or your future self) to understand.


Why Error Handling Matters

  1. **Better User Experience
    **Users don't care why a network request failed; they care that the app didn't freeze. Handling errors allows you to show "Try again later" instead of a broken UI.

  2. Debugging Benefits
    When you catch errors, you can log specific details (like the stack trace) to tools like Sentry or LogRocket. This makes finding and fixing the root cause significantly faster.

  3. Professionalism & Security
    Leaving raw errors exposed in the console can sometimes leak sensitive information about your file structure or API logic. Proper handling keeps your implementation details private and your interface polished.

2 views