Deep Dive in Error Handling in JavaScript
What are we gonna Study?
So, today in this blog we will be studying about error handling more specifically, the topics listed below:
What errors are in JavaScript
Using try and catch blocks
The finally block
Throwing custom errors
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 ☕💝

