当前位置:网站首页>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
 Please add a picture description

原网站

版权声明
本文为[Lurongtao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206231546356329.html

随机推荐