当前位置:网站首页>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推荐
边栏推荐
- Code example of golang date time package: get age, zodiac and constellation based on birthday
- NLP 论文领读|改善意图识别的语义表示:有监督预训练中的各向同性正则化方法
- R语言使用yardstick包的rmse函数评估回归模型的性能、评估回归模型在每个交叉验证(或者重采样)的每一折fold上的RMSE、以及整体的均值RMSE(其他指标mae、mape等计算方式类似)
- Coatnet: marrying revolution and attention for all data sizes
- Summarize the experience of purchasing Alibaba cloud servers
- 如何让销售管理更高效?
- 数学分析_证明_第1章:可数个可数集之并为可数集
- ABP框架之——数据访问基础架构(下)
- 【OpenHarmony】usb gadget 配置hdc功能cfg文件解读
- [tcapulusdb knowledge base] Introduction to tmonitor background one click installation (II)
猜你喜欢

A tour of grpc:01 - Basic Theory

openGauss数据库源码解析系列文章—— 密态等值查询技术详解(上)
![leetcode:30. Concatenate substrings of all words [counter matching + pruning]](/img/a2/91ccaec4cc3dab27c566184b74e561.png)
leetcode:30. Concatenate substrings of all words [counter matching + pruning]

uniapp对接腾讯即时通讯TIM 发图片消息问题

stylegan3:alias-free generative adversarial networks

Innovation strength is recognized again! Tencent security MSS was the pioneer of cloud native security guard in 2022

Server deployment and instructions

golang冒泡排序代码实现

走好数据中台最后一公里,为什么说数据服务 API 是数据中台的标配?

【TcaplusDB知识库】TcaplusDB新增机型介绍
随机推荐
NLP 论文领读|改善意图识别的语义表示:有监督预训练中的各向同性正则化方法
Servlet 3.0的AsyncListener接口
leetcode:面试题 08.13. 堆箱子【自顶而下的dfs + memory or 自底而上的排序 + dp】
Avoid these six difficulties and successfully implement MES system
Openresty Foundation
golang gob实现网络数据的传输
R语言使用timeROC包计算无竞争情况下的生存资料多时间AUC值、使用cox模型、并添加协变量、可视化无竞争情况下的生存资料多时间ROC曲线
数字经济加速落地,能为中小企业带来什么?
How to quickly respond to changing production management needs?
Block, non block, multiplexing, synchronous, asynchronous, bio, NiO, AIO
openGauss数据库源码解析系列文章—— 密态等值查询技术详解(上)
AsyncContext简介
【TcaplusDB知识库】Tmonitor后台一键安装介绍(一)
[tcapulusdb knowledge base] Introduction to tmonitor stand-alone installation guidelines (II)
Code implementation of golang binary search method
SaaS 云工具,产业互联网下的变革利器
Uniapp sends picture messages to Tencent instant messaging Tim
How is it cheaper to open a stock account? Is it safe to open an account online now?
golang goroutine、channel、time代码示例
get_ edges