JavaScript Error Handling: JavaScript Errors: Types
Murphy’s law holds that ultimately whatever may go wrong will also go wrong. In the realm of programming, this fits much too perfectly. Should you build an application, odds are you will produce flaws and other problems. One such a frequent problem with JavaScript are mistakes!
The success of a software product relies on the degree of resolution of these problems by its developers before endangering its consumers. And among all programming languages, JavaScript is infamous for its mediocre error handling style.
Building a JavaScript application increases your likelihood of inadvertently changing data types at some time. If not that, you may find yourself substituting a double equals operator (==) for an unidentified with a null or triple equals operator (===).
Making errors is only human. This is the reason we will walk over all you need to know about managing JavaScript mistakes.
This post will walk you through the fundamental JavaScript mistakes and clarify the several ones you might come into. You will then pick up the skills of seeing and repairing these mistakes. Furthermore included are some pointers on how to properly manage mistakes in manufacturing settings.
What Are JavaScript Errors?
In programming, errors are circumstances whereby a program cannot operate as expected. It can occur when a software tries to access a non-existent file or contacts a web-based API endpoint while there is no network connectivity and lacks knowledge on handling the current job at hand.
These scenarios force the program — which lacks knowledge on how to proceed — to toss mistakes to the user. The software gathers as much data about the mistake as it can then report that it cannot proceed.
Errors vs Exceptions
Generally speaking, most individuals view mistakes and exceptions as one and same. They do, however, differ somewhat yet fundamentally as well.
Let’s consider a brief case to help one better grasp this. Here is a JavaScript definition of an error:
const wrongTypeError = TypeError("Wrong type found, expected character")
And here is how the incorrect Type Error object turns into an exception:
throw wrongTypeError
Still, most people utilize the shorthand form that specifies error objects while throwing them:
throw TypeError("Wrong type found, expected character")
This is how we do things usually. Still, this is one of the reasons developers sometimes confuse mistakes and exceptions. Thus, even if you utilize short cuts to finish your task fast, knowing the principles is quite essential.
JavaScript Errors: Types
JavaScript allows a set of predefined error kinds. Every time the programmer fails expressly to handle faults in the application, the JavaScript runtime automatically chooses and defines them.
This part will go over some of the most often occurring forms of JavaScript errors and help you to know when and why they happen.
RangeError
Setting a variable with a value beyond its permissible values range causes a RangeError. Usually happening when sending a value as an argument to a function, the provided value falls beyond the range of the function’s parameters. Using poorly described third-party libraries can occasionally make fixing difficult as you must know the range of potential values for the parameters to send in the proper value.
ReferenceError
A ReferenceError results from a variable’s reference in your code being incorrect. Either you could be trying to utilize an unavailable variable in your code or you might have overlooked defining a value for the variable prior to utilizing it. All the same, reviewing the stack trace offers enough information to locate and correct the variable reference causing problems.
Reference errors usually arise for some of the following frequent causes:
Typing a variable name incorrectly.
attempting to reach block-scoped variables outside their purview.
Referring to a global variable from an outside library — such as $ from jQuery — before it loads.
Synopsis Error
Since they expose a syntactic code issue, these mistakes are among the easiest to correct. These toss when the program runs the script including the error as JavaScript is a scripting language interpreted rather than compiled. Regarding generated languages, these kinds of mistakes are found during compilation. As such, the app binaries are generated only once these are corrected.
Among the typical causes of Syntactic Errors are:
Absent inverted commas
Missing closing piers
Bad alignment of curly brackets or other letters
Using a linting tool in your IDE can help you to find such mistakes in your IDE before they reach the browser.
TypeError
Among the most often occurring mistakes in JavaScript applications is TypeError. Some value not turning out to be of a particular expected type causes this mistake. Common instances of this kind arise in:
calling things that aren’t techniques.
trying to get features of either null or undefined objects
Handling a string as an integer or vice versa
There are many more scenarios wherein a TypeError might arise. Later on we will review several well-known incidents and learn how to resolve them.
InternalError
An exception inside the JavaScript runtime engine is handled by the InternalError type. It could or might not point to a coding problem.
Usually, InternalError arises in two ways only:
URIsError
URIError results from unauthorized usage of a global URI processing capability such decodeURIComponent. Usually it means that the argument given to the method call did not follow URI guidelines and so was not correctly processed by the function.
Usually, diagnosing these mistakes is simple as you just need to look at the justifications for malformation.
Evaluate error
An EvalError results from a call to the eval() function producing an error. JavaScript code kept in strings is ran using the eval() method. But since security concerns greatly discourage using the eval() method and the new ECMAScript standards do not throw the EvalError class anymore, this error type remains just to keep backward compatibility with outdated JavaScript programs.
Should you be working on an earlier JavaScript version, you might run across this issue. In any event, for any exceptions it is advisable to look at the code carried out in the eval() function call.
designing custom error types
Although JavaScript provides a sufficient range of error type classes to address most situations, you may always construct a new error type should the list fall short of your need. The basis of this adaptability is JavaScript’s ability to let you toss anything literally with the throw command.
These remarks are thus theoretically totally legal:
throw 8
throw "An error occurred"
But discarding a basic data type leaves out specifics on the issue, including type, name, or accompanying stack trace. The Error class offers a means to correct this and unify the error handling mechanism. Using basic data types while throwing exceptions discourages as well.
Custom error classes may be created by extending the Error class. Here is a rudimentary illustration of how you may accomplish this:
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
And you may apply it as follows:
throw ValidationError("Property not found: name")
And then the instanceof keyword will help you to find it:
try {
validateForm() // code that throws a ValidationError
} catch (e) {
if (e instanceof ValidationError)
// do something
else
// do something else
}
Top 3 Most Common Errors in JavaScript
It’s time to review some of the most often occurring mistakes you will run into when developing JavaScript code now that you know the typical ones and how to build your own.
1. Uncaught RangeError
Google Chrome makes this mistake in several different contexts. First, it can occur should you call a recursive function and it does not stop. The Chrome Developer Console lets you view this yourself:
2. Uncaught TypeError: Cannot read property
Among the most often recurring mistakes in JavaScript is this one. You run this mistake trying to access a property or execute a method on an unidentified object. Running the following code in a Chrome Developer console will help you to replicate it rather effortlessly.
var func
func.call()
Among the several likely reasons of this mistake is an unclear object. An inappropriate state setup during UI rendering might also be a major factor contributing to this problems. This is a practical illustration from a React application:
import React, { useState, useEffect } from "react";
const CardsList = () => {
const [state, setState] = useState();
useEffect(() => {
setTimeout(() => setState({ items: ["Card 1", "Card 2"] }), 2000);
}, []);
return (
<>
{state.items.map((item) => (
<li key={item}>{item}</li>
))}
</>
);
};
export default CardsList;
Starting in an empty state container, the program receives some things two seconds later. The delay serves to replicate a network call. Your network is rather fast, but you will still have a little latency that will cause the component to show at least once to be compromised. Trying to launch this program will cause the following error: