当前位置:网站首页>JS common error reporting and exception capture
JS common error reporting and exception capture
2022-06-23 16:32:00 【Lurongtao】
JS Common error reporting and exception capture
In development , Sometimes , We spent hours writing about Js Code , Let's debug the tour , The console is red , In an instant, ten thousand grass mud horses came galloping forward .
thus , Main records of this paper Js Some common types of errors , And common error reporting information , Analyze the cause of the error , And give treatment . And we will introduce several ways to catch exceptions .
notes : This article uses Google explorer to verify , Different tourist devices , Reporting errors can be different .
Common types of errors
- RangeError: Mark an error , Trigger when the set value exceeds the corresponding range . such as ,new Array(-20).
- ReferenceError: Wrong reference type , An error that occurs when a nonexistent variable is referenced . such as :console.log(a).
- SyntaxError: Grammar mistakes . such as if(true) {.
- TypeError: Type error , An error that occurs when the type of the value is not the expected type .
Common mistakes
RangeError:` `Maximum` `call` `stack` `size` `exceeded
meaning : Maximum stack size exceeded
Why report a mistake ?
Using recursion consumes a lot of stacks , Causes the browser to throw an error , Because the memory allocated to is not infinite .
Take a chestnut :
function pow(x, n) {
return x * pow(x, n - 1);
}
pow(10,5)
Treatment method :
When using recursion , Set a condition to terminate recursion , Otherwise, there will be an infinite loop , Until you run out of call stack space .
function pow(x, n) {
if (n == 1) return x
return x * pow(x, n - 1);
}
pow(10,5)
ReferenceError:` `"x"` `is` `not` `defined
meaning :“x” Undefined
Why report a mistake ?
When you reference an undefined variable , Throw a ReferenceError; When you use variables , This variable must be declared , Or you can make sure it's in your current script or scope (scope) Available in the .
Take a chestnut :
// Variable not declared
console.log(a)
fn()
// Wrong scope
function sum() {
let number1 = 20,number2 = 30;
return number1 + number2;
}
console.log(number1)
Treatment method :
Variable usage var|let|const Statement
Raise the scope of a variable
// Variable not declared
let a;
function fn() {
};
console.log(a);
fn();
// Wrong scope
let number1 = 20, number2 = 30;
function sum() {
return number1 + number2;
}
console.log(number1)
SyntaxError:` `Identifier` `'x'` `has` `already` `been` `declared
meaning : Identifier declared
Why report a mistake ?
A variable name already appears as a parameter , It's using again let Once again .
Take a chestnut :
// let Repeat statement
let a = 0;
let a = 2;
// In the function, the parameter already appears , The function uses let To declare
function fn(arg) {
let arg = []
}
SyntaxError:` `Invalid` `or` `unexpected` `token
meaning : Capture invalid or unexpected tags
Why report a mistake ?
There are illegal characters in the code or the necessary identifier is missing , Like the minus sign ( - ) And connectors ( – ) , Or double quotation marks ( " ) Double quotation marks with Chinese ( “ ).
Take a chestnut :
// Missing characters
let str = 'string;
let colors = ['#000', #333', '#666'];
// Use special characters
let str1 = 'string";
let str2 = 5#5;
// Mismatch character ( Use Chinese quotation characters )
let str3 = ‘string’;
Treatment method
Check for special characters or missing characters .
SyntaxError:` `Unexpected` `end` `of` `input
meaning : Unexpected termination input
Why report a mistake ?
Brackets or quotation marks do not match in some places in the code, missing , The lack of ()、[]、{} etc. .
Take a chestnut :
// Missing brackets
if(true)
let obj = {
id: 1
let arr = [1,2,3
// Missing end sign
(function () {
console.log('hello world')
}()
Treatment method :
Check for special characters or missing characters , Brackets need to be paired .
TypeError:` `Cannot` `read` `property` `'x'` `of` `undefined
TypeError:` `Cannot` `set` `property` `'x'` `of` `undefined
meaning : Unable to read property ‘x’, Unable to set property ‘x’
Why report a mistake ?
Access or settings are undefined (undefined) or null This error occurs when the property of the value is .
Take a chestnut :
// undefined
let a = undefined
a.id // Read
a.id = 1 // Set up
// null
let b = null
b.id // Read
b.id = 2 // Set up
null.filter(item=>item)
Treatment method :
There are ways to avoid this mistake . A simple and suitable method for small attribute chains is to use logical operators &&.
let obj = undefined
console.log(obj&&obj.id)
TypeError:` `'x'` `is` `not` `a` `constructor
meaning : Express ‘x’ Not a constructor
Why report a mistake ?
Use an object or variable that is not a constructor to use as a constructor . such as :new 10.
Take a chestnut :
let Car = 1;
new Car();
new Math();
Treatment method :
Use the correct constructor .Generator functions It can't be used as a constructor .
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
SyntaxError:Invalidregularexpressionflags meaning : Invalid regular expression flag
Why report a mistake ?
Invalid regular expression token in code .
Take a chestnut :
let reg = /foo/bar;
Treatment method :
let reg = /foo/g;
DOMException:` `Failed` `to` `execute` `'open'` `on` `'XMLHttpRequest':` `Invalid` `URL
meaning : invalid Url
Why report a mistake ?
In the use of ajax When asked url error , Cause the request to fail .
Take a chestnut :
function createXHR(url) {
let xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('user=admin');
xhr.onreadystatechange = function () {
}
}
createXHR('http://192.168.10.8080') // error url
createXHR('http:/192.168.10:8080/open') // The lack of /, notes : Some of them will be completed automatically
Treatment method :
Check url Whether the request is correct , Ensure the integrity of the request path .
createXHR('http://192.168.10:8080')
Exception debugging and capture
try/catch,Js A pattern for handling exceptions in ,try For code where errors may occur ,catch Handling of errors
try{
// Code that can cause errors
}catch(error) {
// Error handling
}
Take a chestnut :
try{
console.log(a)
}catch(error) {
// Print error messages
console.log(error) // ReferenceError: a is not defined
}
throw, Used to throw a user-defined exception , Execution will be stopped .
function getUserName(name) {
if(!name) throw new Error(' Invalid user name ');
return name;
}
getUserName()
Promise Exception handling ,Promise In execution , Bring it with you try…catch Exception handling , When something goes wrong , Make a mistake Rejact function .
new Promise((resolve, reject) => {
throw new Error('error!');
}).catch(alert);
console.log() Method , In the tour , Use console.log Print javaScript Value .
let value = ' You are the best , A great bai !'
console.log(value)
debugger Breakpoint debugging , Used to stop execution JavaScript, And call the debug function .
let value = 15;
debugger
document.querySelector('body').innerHTML = ' You are the best , A great bai !'
summary
Don't panic when you report a mistake , Sometimes it's that simple , Tap on the code , Familiar with some common error reporting information , It is convenient to quickly locate the cause of error when reporting an error .
-End -
* Lu Rongtao front-end learning exchange Q Group 858752519
Add group notes :CSDN recommend 
边栏推荐
- leetcode:30. 串联所有单词的子串【Counter匹配 + 剪枝】
- 数学分析_证明_第1章:可数个可数集之并为可数集
- R语言使用magick包的image_scale函数对图像进行缩放(resize)、可以自定义从宽度或者高度角度进行缩放
- 港股多支个股表现活跃,引发投资者对港股市场回暖猜想与关注
- 谈谈redis缓存击穿透和缓存击穿的区别,以及它们所引起的雪崩效应
- 元宇宙带来的社会结构和资本制度演变
- R language uses the image of magick package_ The scale function resizes the image. You can customize the scaling from the angle of width or height
- 2022九峰小学(光谷第二十一小学)生源摸底
- 《ThreadLocal》
- 供求两端的对接将不再是依靠互联网时代的平台和中心来实现的
猜你喜欢
![[tcapulusdb knowledge base] Introduction to tmonitor stand-alone installation guidelines (I)](/img/7b/8c4f1549054ee8c0184495d9e8e378.png)
[tcapulusdb knowledge base] Introduction to tmonitor stand-alone installation guidelines (I)

聚焦:ZK-SNARK 技术

亚朵更新招股书:继续推进纳斯达克上市,已提前“套现”2060万元

npm install 问题解决(nvm安装与使用)

机器人方向与高考选专业的一些误区
![[tcapulusdb knowledge base] tcapulusdb tmonitor module architecture introduction](/img/7b/8c4f1549054ee8c0184495d9e8e378.png)
[tcapulusdb knowledge base] tcapulusdb tmonitor module architecture introduction

【TcaplusDB知识库】Tmonitor后台一键安装介绍(一)

golang数据类型图

Apache基金会正式宣布Apache InLong成为顶级项目

数学分析_证明_第1章:可数个可数集之并为可数集
随机推荐
R语言使用magick包的image_scale函数对图像进行缩放(resize)、可以自定义从宽度或者高度角度进行缩放
stylegan1: a style-based henerator architecture for gemerative adversarial networks
JSON in MySQL_ Extract function description
元宇宙带来的社会结构和资本制度演变
Block, non block, multiplexing, synchronous, asynchronous, bio, NiO, AIO
leetcode:面试题 08.13. 堆箱子【自顶而下的dfs + memory or 自底而上的排序 + dp】
[openharmony] USB gadget configuration HDC function cfg file interpretation
你女朋友也能读懂的LAMP架构
[tcapulusdb knowledge base] Introduction to tmonitor stand-alone installation guidelines (II)
[solution] NPM warn config global ` --global`, `--local` are deprecated Use `--location=global`
NPM install problem solving (NVM installation and use)
Ten thousand words introduction, detailed explanation of the core technical points of Tencent interview (t1-t9), and arrangement of interview questions
供求两端的对接将不再是依靠互联网时代的平台和中心来实现的
二分查找法思路分析
Does the enterprise want to use the MES system? These conditions have to be met
npm install 问题解决(nvm安装与使用)
What are the risks of opening a fund account? Is it safe to open an account
[tcapulusdb knowledge base] tcapulusdb tmonitor module architecture introduction
坚持五件事,带你走出迷茫困境
多年亿级流量下的高并发经验总结,都毫无保留地写在了这本书中