7 JS native error types you should know

Time:2022-5-9
catalogue
  • summary
  • 1. RangeError
  • 2. ReferenceError
  • 3. SyntaxError
  • 4. TypeError
  • 5. URIError
  • 6. EvalError
  • 7. InternalError
  • summary

summary

From the browser console to run node JS terminal, we will see errors everywhere. The focus of this article is to outline the types of errors we may encounter in JS development.

Tip: good error tips can lead to the difference between rapid and painless development experience and slow and painful development experience. When writing reusable code, make sure you are writing clear and understandable error handling code.

1. RangeError

This error is thrown when the number exceeds the allowed value range.

for example


const l = console.logconst arr = [90,88]
arr.length=90**99

We have an array with two element arr. Next, try to expand the array to contain 90 * * 99 = = 2.9512665430652753e + 193 elements.

This number is beyond the range that the array size can grow. Running it will throw rangeerror:

$ node errors

errors.js:4

arr.length=90**99

 ^RangeError: Invalid array length

Because we want to increase the size of the ARR array, which is beyond the range specified in JS.

2. ReferenceError

This error is raised when a reference to a variable or project is broken. That is because the variable or item does not exist.

for example


const l=console.logconst cat = "cat"
cat
dog

A variable cat is initialized to “cat”. Next, the cat variable and dog variable are referenced. Cat variable exists, but dog variable does not exist.

Cat will return “cat” and dog will raise a reference error because the name dog cannot be found in the environment record.

$ node errors

errors.js:3

dog

^ReferenceError: dog is not defined

Whenever we create or define a variable, the variable name is written to the environment record. Environment records are like key value storage,

+————-+

| Key | Value |

—————

| cat | “cat” |

+————-+

Whenever we reference a variable, it stores the variables defined in the program. When the environment value is found in the record and the value is extracted and returned, the name of the variable will be used as the keyword to search in the environment record. Call a function that has not been defined.

Now, when we create or define a variable that has no assignment. A variable writes its key to the environment record as a variable name, but its value remains undefined.

var catenv record

+—————–+

| Key | Value |

——————-

| cat | undefined |

+—————–+

When assigning a value to a variable later, the variable will be searched in the environment record. When it is found that it has no value defined, the assignment will be overwritten.

var cat

cat = “cat”env record

+————-+

| Key | Value |

—————

| cat | “cat” |

+————-+

Therefore, when the variable name cannot be found in the environment record, the JS engine will raise referenceerror.

+————-+

| Key | Value |

—————

| cat | “cat” |

+————-+cat // “cat”, yes, 🙂 it’s there

dog // 🙁 what’s this? can’t find it

Note: undefined variables will not throw referenceerror because the value in the environment record has not been set.

3. SyntaxError

This is the most common mistake. This error occurs when we enter code that the JS engine cannot understand.

The JS engine caught this error during parsing. In JS engine, our code goes through different stages before we can see the results on the terminal.

  • Tokenization
  • analysis
  • explain

Tokenization decomposes the source of code into units. At this stage, numbers, keywords, words and operators will be classified and marked respectively.

Next, the generated tag stream will be passed to the parsing phase and processed by the parser. This is where the AST is generated from the tag stream. AST is an abstract representation of code structure.

In the two stages of tokenization and parsing, if the syntax of our code does not comply with the syntax rules of JS, this stage will fail and syntaxerror will be raised. For example:


const l = console.loglet cat h = "cat"

What does “H” stand for in the code? This “H” breaks the code.

$ node errors

errors.js:3

let cat h = “cat”

 ^SyntaxError: Unexpected identifier

Look, node JS points out the problem. It said “H” was unexpected, and it broke the declaration of the cat variable.

Therefore, it can be said that syntax errors occur during parsing or compilation.

4. TypeError

Typeerror is used to indicate that the operation failed when there is no indication of the appropriate failure reason in other nativeerror objects.

Typeerror occurs when an operation is performed on the wrong data type, for example:

If we try to convert numbers to uppercase, as follows:


const num = 123
num.toUpperCase()

This raises a typeerror

$ node errors

errors.js:4

num.toUpperCase()

 ^TypeError: num.toUpperCase is not a function

Because the touppercase function requires a string data type. The touppercase function is intentionally generic; It does not need its this value to be a string object. Therefore, it can be transferred to other kinds of objects as methods.

Only strings can be converted to uppercase or lowercase. If we call touppercase function on objects, Boolean, symbol, null and undefined data types, we will get typeerror because the data type it operates on is wrong.

5. URIError

This indicates the use of a global URI handler that is not compatible with its definition.

The URI (uniform resource indicator) in JS has the following functions: decodeuri, decodeuricomponent, etc.

If we call any of them with the wrong parameters, we will get a urierror.


decodeURI("%")
^URIError: URI malformed

Encodeuri is used to get the uncoded version of the URI. ‘%’ is not a correct URI, so urierror was thrown.

Urierror is raised when there is a problem with URI encoding or decoding.

6. EvalError

This is used to identify errors when using the global eval() function.

According to ecmascec 2018 Edition:

This exception is not currently used by this specification. It is retained for compatibility with previous versions of this specification.

7. InternalError

This error occurs inside the JS engine, especially when it has too much data to process and the stack growth exceeds its critical limit.

This problem occurs when the JS engine is inundated by too much recursion and switching


switch(num) {
 case 1:
 ...
 break
 case 2:
 ...
 break
 case 3:
 ...
 break
 case 4:
 ...
 break
 case 5:
 ...
 break
 case 6:
 ...
 break
 case 7:
 ...
 break
 ... up to 1000 cases
 }

The following is a simple example of excessive recursion:


function foo() {
    foo()
}
foo()

summary

As we said, everyone makes mistakes. As far as we knock the code, this is a stable event. To overcome this, we need to know the types of native errors that can be thrown. They are listed in this article and some examples are provided to illustrate how they are triggered.

So whenever an error is caused in the terminal or browser, you can easily find the location and way of the error, and can write better and less error prone code.

The above is the details of the seven JS native error types you should know. For more information about JS native error types, please pay attention to other relevant articles of developeppaer!

Recommended Today

VBS tutorial: introduction to regular expressions – priority order

Priority order After constructing a regular expression, it can be evaluated like a mathematical expression, that is, it can be evaluated from left to right and in a priority order. The following table lists the priority order of various regular expression operators from the highest priority to the lowest priority: Operator describe \ Escape character […]