Skip to main content

Command Palette

Search for a command to run...

Deep Dive in Error Handling in JavaScript

Updated
5 min read

What are we gonna Study?

So, today in this blog we will be studying about error handling more specifically, the topics listed below:

  1. What errors are in JavaScript

  2. Using try and catch blocks

  3. The finally block

  4. Throwing custom errors

  5. Why error handling matters

This is one of the most important topic for both backend and frontend...

It's my guarantee that you would not have any doubts regarding to this after reading this blog, you just sit back relaxed, gather all the focus here, and have a tea/coffee with you ☕


What Errors are In JavaScript

  • Error is basically an object... yeah you heard it right it's an object that represents the problems caused during the execution of the code.

  • When an error occurs, it halts the execution of code any further until and unless it is handled.


Types of Errors

In Javascript, infact any other programming language, we have mulitple types of built-in errors.

Each one of them represent different kind of problem caused.

  • SyntaxError: This error occurs when your code violates the rules of the language (for exmaple: not putting parentheses in function).

  • ReferenceError: Caused when you try to access a variable or a function that has not been declared yet (for exmaple: using let variable before its declaration in code).

  • TypeError: Occurs when a values's expected type doesn't matches it's type (for exmaple: applying array methods to an object).

  • RangeError: Occurs when a numeric value goes beyond its valid range (for exmaple: array length > 2^32 - 1).

  • URIError: Occurs when global URI functions (like decodeURIComponent) are passed invalid parameters.

  • AggregateError: Represents multiple errors wrapped up into a single object, common in Promise.any().

  • InternalError: Occurs when JavaScript engine faces an intenal limitation (for exmaple: too much recursion).


What is Error Object

A built in object that contains 3 key prooperties:

  • name: Tells about the type of the error.

  • Message: A human readable description of what went wrong.

  • Stack: Non-standard but still supported by many, this property provides stack trace that shows the line number and file paths where the error was originated.

Pretty much about errors isn't it? Now let's read about error-handling


Try-Catch-Finally Blocks

Try-Catch and Finally are blocks of code that we use for handling errors.

The syntax looks like this:

try {
  // All code to execute
} catch (error) {
  //  All Error Handling
} finally {
  // Supplementary Code (optional)
}

Try block

  • Inside the try block we write all the code that might result in error.

  • It executes the code, if no error occurs catch block doesn't runs but if error occurs it passes that error to catch block.

  • It is mandatory to write while error handling with these blocks, the rest two blocks are not mandatory but you have to keep one of them to be syntactically correct.


Catch Block

  • Here, we write all the code that will handle error.

  • It takes error as an argument from the try block.

  • While it is not mandatory to write it is highly recommended to write because try can not handle errors alone.


FInally Block

  • Here, we write all the clean up code.

  • It executes in both scenario, which means it will be executed if there is error and it will be executed if there isn't any error as well.

  • Again not mandatory.


Throwing Custom Errors

To throw your own custom errors you can use the throw keyword and pass the error.

async function fetchData() {
  try {
    const data = await fetch(
      'https://jsonplaceholder.typicode.com/todos'
    )
    return data
  } catch (error) {
    console.log(error.message)
    throw new Error('Failed Fetching Data')
  } finally {
    console.log('Processed Data Fetching')
  }
}

See how we threw an error of our will...

But there is one more way to do it that will help you make your own error types:

class FetchingError extends Error {
  constructor(message, field) {
    super(message); // Call the parent constructor
    this.name = "FetchingError"; // Set custom error name
  }
}

async function fetchData() {
  try {
    const data = await fetch(
      'https://jsonplaceholder.typicode.com/todos'
    )
    return data
  } catch (error) {
    console.log(error.message)
    throw new FetchingError('Failed Fetching Data')
  } finally {
    console.log('Processed Data Fetching')
  }
}

What we did is that we took all the properties of Error class and then customized it as we wanted, no rocket science if you know OOPS, if not go check out my OOPS blog.


Why Error Handling Matters

Error handling have many benifits that are listed below:

  • It ensures your application runs stably without crashing due to any unexpected error.

  • It enhances User Experience (UX) by showing them proper issue instead of a broken screen.

  • Easier debugging and maintainence for devlopers, because it becomes easier to point the error.

A few more benifits are remaining not much just 1-2 and i think you should tell me that in the comments ;)


Wrap Up!

So guys, that was it for today's blog i really appreciate if you managed to get all the way till here, most of the people don't have even this much of attention span and patience.

So, that was it from my side today, i'll catch you up in next blog, until then keep coding and drinking your tea/coffee ☕💝

JavaScript: Everything you should know

Part 16 of 26

This is your ultimate guide towards JavaScirpt, this series of articles include - JavaScript Operators: The Basics You Need to Know - Understanding Variables and Data Types in JavaScript - Template Literals in JavaScript - Control Flow in JavaScript: If, Else, and Switch Explained - Array Methods You Must Know - JavaScript Arrays 101 - Function Declaration vs Function Expression: What’s the Difference? - Arrow Functions in JavaScript: A Simpler Way to Write Functions - Understanding Objects in JavaScript - Spread vs Rest Operators in JavaScript - Destructuring in JavaScript - Map and Set in JavaScript - Understanding Object-Oriented Programming in JavaScript - Understanding the this Keyword in JavaScript - The new Keyword in JavaScript - The Magic of this, call(), apply(), and bind() in JavaScript - Array Flatten in JavaScript - String Polyfills and Common Interview Methods in JavaScript - Synchronous vs Asynchronous JavaScript - Callbacks in JavaScript: Why They Exist - JavaScript Promises Explained for Beginners - Promise Methods Explained: CID Analogy - Async/Await in JavaScript: Writing Cleaner Asynchronous Code - Error Handling in JavaScript: Try, Catch, Finally - JavaScript Modules: Import and Export Explained - The Part of Events You Never See The following 26 articles and topics are covered

Up next

Synchronous vs Asynchronous JavaScript

What are we gonna study? Today, we are going to study about topics that are given below: What synchronous code means What asynchronous code means Why JavaScript needs asynchronous behavior Problem

More from this blog

L

Learning Tech

61 posts

A Blog with dozens of articles on different langauges as well as frameworks, This isn't just for you to learn, i crafted it thinking that this could be my future reference as well

It covers Networking, Web Development, Mobile Developement and very soon GenAI too!