当前位置:网站首页>JS常见的报错及异常捕获
JS常见的报错及异常捕获
2022-06-23 15:46:00 【陆荣涛】
JS常见的报错及异常捕获
在开发中,有时,我们花了几个小时写的Js 代码,在游览器调试一看,控制台一堆红,瞬间一万头草泥马奔腾而来。
至此,本文主要记录Js 常见的一些错误类型,以及常见的报错信息,分析其报错原因,并给予处理方法。并且将介绍几种捕获异常的方法。
注:本文使用的谷歌游览器验证,不同的游览器,报错可能会不一样。
常见的错误类型
- RangeError:标记一个错误,当设置的数值超出相应的范围触发。比如,new Array(-20)。
- ReferenceError:引用类型错误,当一个不存在的变量被引用时发生的错误。比如:console.log(a)。
- SyntaxError:语法错误。比如 if(true) {。
- TypeError:类型错误,表示值的类型非预期类型时发生的错误。
常见的错误
RangeError:` `Maximum` `call` `stack` `size` `exceeded
含义:超出了最大的堆栈大小
为什么报错?
在使用递归时消耗大量堆栈,导致游览器抛出错误,因为游览器给分配的内存不是无限的。
举个栗子:
function pow(x, n) {
return x * pow(x, n - 1);
}
pow(10,5)
处理办法:
使用递归的时候,设定一个条件来终止递归,否则会无限循环,直到用尽调用堆栈空间为止。
function pow(x, n) {
if (n == 1) return x
return x * pow(x, n - 1);
}
pow(10,5)
ReferenceError:` `"x"` `is` `not` `defined
含义:“x”未定义
为什么报错?
当你引用一个没有定义的变量时,抛出一个ReferenceError; 当你使用变量的时候,这个变量必须要声明,或者你可以确保它在你当前的脚本或作用域 (scope) 中可用。
举个栗子:
// 变量未声明
console.log(a)
fn()
// 错误的作用域
function sum() {
let number1 = 20,number2 = 30;
return number1 + number2;
}
console.log(number1)
处理办法:
变量使用var|let|const 声明
提升变量的作用域
// 变量未声明
let a;
function fn() {
};
console.log(a);
fn();
// 错误的作用域
let number1 = 20, number2 = 30;
function sum() {
return number1 + number2;
}
console.log(number1)
SyntaxError:` `Identifier` `'x'` `has` `already` `been` `declared
含义: 标识符已申明
为什么报错?
某个变量名称已经作为参数出现了,又在使用let再次声明。
举个栗子:
// let 重复声明
let a = 0;
let a = 2;
// 在函数中参数已经出现,函数里使用let重新声明
function fn(arg) {
let arg = []
}
SyntaxError:` `Invalid` `or` `unexpected` `token
含义:捕获无效或意外的标记
为什么报错?
代码中有非法的字符或者缺少必要的标识符号,比如减号 ( - ) 与连接符 ( – ) ,或者是英文双引号 ( " ) 与中文双引号 ( “ )。
举个栗子:
// 遗漏的字符
let str = 'string;
let colors = ['#000', #333', '#666'];
// 使用特殊字符
let str1 = 'string";
let str2 = 5#5;
// 错配字符(使用中文引号字符)
let str3 = ‘string’;
处理办法
检查是否有特殊字符或者是否遗漏一些字符。
SyntaxError:` `Unexpected` `end` `of` `input
含义:意外的终止输入
为什么报错?
代码中某些地方的括号或引号不匹配缺失,缺少()、[]、{}等。
举个栗子:
// 缺少括号
if(true)
let obj = {
id: 1
let arr = [1,2,3
// 缺少结束符号
(function () {
console.log('hello world')
}()
处理办法:
检查是否有特殊字符或者是否遗漏一些字符,括号需要配对出现。
TypeError:` `Cannot` `read` `property` `'x'` `of` `undefined
TypeError:` `Cannot` `set` `property` `'x'` `of` `undefined
含义:无法读取属性‘x’, 无法设置属性 ‘x’
为什么报错?
访问或设置未定义(undefined)或null值的属性时会发生这种报错。
举个栗子:
// undefined
let a = undefined
a.id // 读取
a.id = 1 // 设置
// null
let b = null
b.id // 读取
b.id = 2 // 设置
null.filter(item=>item)
处理办法:
有一些方法可以避免这种错误。一种简单且适用于小型属性链的方法是使用逻辑运算符&&。
let obj = undefined
console.log(obj&&obj.id)
TypeError:` `'x'` `is` `not` `a` `constructor
含义:表示 ‘x’不是构造函数
为什么报错?
使用不是构造器的对象或者变量来作为构造器使用。比如:new 10。
举个栗子:
let Car = 1;
new Car();
new Math();
处理办法:
使用正确的构造函数。Generator functions 也不能作为构造器来使用。
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
SyntaxError:Invalidregularexpressionflags含义:正则表达式标志无效
为什么报错?
在代码中出现了无效的正则表达式的标记。
举个栗子:
let reg = /foo/bar;
处理办法:
let reg = /foo/g;
DOMException:` `Failed` `to` `execute` `'open'` `on` `'XMLHttpRequest':` `Invalid` `URL
含义:无效的Url
为什么报错?
在使用ajax 请求时url错误,导致请求失败。
举个栗子:
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') // 错误url
createXHR('http:/192.168.10:8080/open') // 缺少 /,注:有些游览器会自动补全
处理办法:
检查url 请求是否正确,保证请求路径的完整。
createXHR('http://192.168.10:8080')
异常调试及捕获
try/catch,Js中处理异常的一种模式,try用于可能会发生错误的代码,catch对错误的处理
try{
// 可能会导致错误的代码
}catch(error) {
// 错误处理
}
举个栗子:
try{
console.log(a)
}catch(error) {
// 打印错误信息
console.log(error) // ReferenceError: a is not defined
}
throw,用来抛出一个用户自定义的异常,执行将被停止。
function getUserName(name) {
if(!name) throw new Error('用户名无效');
return name;
}
getUserName()
Promise 的异常处理,Promise执行中,本身自带try…catch的异常处理,出错时,将错误Rejact函数。
new Promise((resolve, reject) => {
throw new Error('error!');
}).catch(alert);
console.log() 方法,在游览器中,使用console.log打印javaScript的值。
let value = '你最棒了,点个赞呗!'
console.log(value)
debugger 断点调试,用于停止执行 JavaScript,并调用调试函数。
let value = 15;
debugger
document.querySelector('body').innerHTML = '你最棒了,点个赞呗!'
总结
报错的时候别慌,有时候就是那么简单,根据这些代码敲一敲,熟悉一些常用的报错信息,便于在报错的时候快速的定位到报错原因。
-End -
*陆荣涛前端学习交流Q群858752519
加群备注:CSDN推荐
边栏推荐
- NLP 论文领读|改善意图识别的语义表示:有监督预训练中的各向同性正则化方法
- Drag the child file to the upper level
- leetcode:30. Concatenate substrings of all words [counter matching + pruning]
- Thinking analysis of binary search method
- [tcapulusdb knowledge base] Introduction to new models of tcapulusdb
- 《ThreadLocal》
- Golang对JSON文件的写操作
- js中 if 直接判断 数据类型 结果举例
- Pytorch: saving and exporting models
- 二分查找法思路分析
猜你喜欢

《ThreadLocal》

【解决】npm WARN config global `--global`, `--local` are deprecated. Use `--location=global`
![[tcapulusdb knowledge base] Introduction to tmonitor background one click installation (I)](/img/d7/3a514fb75b3df487914a8db245ab89.png)
[tcapulusdb knowledge base] Introduction to tmonitor background one click installation (I)

CoAtNet: Marrying Convolution and Attention for All Data Sizes翻译

Coatnet: marrying revolution and attention for all data sizes

【TcaplusDB知识库】Tmonitor后台一键安装介绍(一)
![[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)

IFLYTEK neuroimaging disease prediction program!

golang二分查找法代码实现

Golang对JSON文件的写操作
随机推荐
二分查找法思路分析
Stick to five things to get you out of your confusion
[tcapulusdb knowledge base] Introduction to new models of tcapulusdb
Interpreting the 2022 agile coaching industry status report
面渣逆袭:MySQL六十六问!建议收藏
Zhongda face sketch FERET database (cufsf)
提高效率 Or 增加成本,开发人员应如何理解结对编程?
Now I want to buy stocks. How do I open an account? Is it safe to open a mobile account?
R语言使用magick包的image_scale函数对图像进行缩放(resize)、可以自定义从宽度或者高度角度进行缩放
After the model is created, initialize the variables in con2d, convtranspose2d, and normalized batchnorm2d functions
泰山OFFICE技术讲座:使用字体斜体的四种情形
Quartz
js 递归json树 根据 子id 查 父id
R语言使用colorblinr包模拟色盲视觉、将已有的ggplot2可视化结果图像使用edit_colors函数编辑转化为色盲视觉友好的可视化结果、并自定设置色盲形式、色盲严重级别
Implementation of network data transmission by golang Gob
stylegan1: a style-based henerator architecture for gemerative adversarial networks
Uniapp sends picture messages to Tencent instant messaging Tim
解读2022年度敏捷教练行业现状报告
Batch registration component
走好数据中台最后一公里,为什么说数据服务 API 是数据中台的标配?