js代码可能会因为某些原因,导致出错,进而整个后续代码有可能都被阻断。直接影响线上的稳定性
console.log(111)
// 预期 a = {}
// 结果
a = undefined
a.a = 1
console.log(222) // js代码不能执行到这一行
这个代码很明显会报错,在a.a = 1这一行开始报错,后续的js代码被阻断了,console.log(222)打印不出来
console.log(111)
try {// 预期 a = {}// 结果a = undefineda.a = 1
} catch (e) {console.error(e)
}
console.log(222) // js代码可以执行到这一行
try {// 预期 a = {} // 结果 a = undefined a.a = 1
} catch (e) {console.error(e)// 公司内部的上报函数someReportFunction('sendEvent', {name: 'try_catch_error',params: {errorMsg: e.message,errorStack: e.stack},});
}
随便点开一篇文章,就有人在误人子弟,教别人用 throw, throw这个东西是不能乱用的,因为他会阻断代码,重要的事情说三遍,throw会阻断代码,throw会阻断代码,throw会阻断代码
例如:
console.log(111)
try {// 预期 a = {}// 结果a = undefineda.a = 1
} catch (e) {console.error(e)throw e // throw会阻断代码,导致下面不执行
}
console.log(222) // 不能执行到这一行
当然throw也不是一无是处,但是,他只能在try{ 里面使用 },不能在try之外的地方使用throw,包括catch
console.log(111)
try {throw new Error(111)
} catch (e) {console.error(e)
}
console.log(222)
function getData () {if (...) {...} else {throw new Error(111)}
}
console.log(111)
try {getData()
} catch (e) {console.error(e)
}
console.log(222)
console.log(111111111)
try {setTimeout(() => {a = undefineda.a = 1 // 代码被阻断于此console.log('error') // 不能执行到这一行}, 0)
} catch (e) {console.error(e) // 异步代码catch不到
}
console.log(222222222)setTimeout(() => {console.log('setTimeout') // 浏览器可以执行到这一行,node的不行(node14和16版本都test了)
}, 2000)
// a.js
console.log(111111111)
try {require('./b.js')
} catch (e) {console.log('error') // 错误会被正常catch到console.error(e)
}
console.log(222222222)setTimeout(() => {console.log('setTimeout')
}, 2000)// b.js
console.log(1)
a = undefined
a.a = 1
console.log(2)// 结果打印 (require被正常捕获)
111111111
1
error
TypeError: Cannot set property 'a' of undefined......
222222222
setTimeout
// a.js
console.log(111111111)
try {import('./b.js')
} catch (e) {console.log('error') // 错误没有被catch到console.error(e)
}
console.log(222222222)setTimeout(() => {console.log('setTimeout')
}, 2000)// b.js
console.log(1)
a = undefined
a.a = 1
console.log(2)// 结果打印 (import的 错误没有被catch到)
111111111
222222222
1
(node:92673) UnhandledPromiseRejectionWarning: TypeError: Cannot set property 'a' of undefined...
setTimeout
正确捕获import()的方式:其实import()是一个promise,用promise的方法去catch就好了import('./b.js') .catch(e => { console.log('error') console.error(e) }) 结论:
try catch 不能捕获import()模块的错误,require可以被捕获
import() 用promise的方法去catch就好了
背景:
最近还整理一份JavaScript与ES的笔记,一共25个重要的知识点,对每个知识点都进行了讲解和分析。能帮你快速掌握JavaScript与ES的相关知识,提升工作效率。




有需要的小伙伴,可以点击下方卡片领取,无偿分享