跳到主要内容

如何捕获 JS 程序中的异常?

第一种 try catch

// 高风险的地方
try{
// todo
console.log(a)
}catch (err) {
// 手动捕获 catch
console.log(err) // ReferenceError: a is not defined at test.js:4
}finally {
// todo
console.log('finally') // finally
}

第二种用 window.onerror

// 自动捕获
window.onerror = function (message,source,lineNum,colNum,error) {
// 第一,对跨域的js,如 CDN 的,不会有详细的报错信息
// 第二,对于压缩的 js,还需要配合 sourceMap 反查到未压缩代码的行,列
console.log('msg',message)
console.log('source',source)
console.log('lineNum',lineNum)
// msg Uncaught Error: this is the error happened
// source http://localhost/test/test.js
// lineNum 24
}
throw new Error('this is the error happened');