javascript中的Error收集 - pod4g/tool GitHub Wiki
零. JavaScript Error行为对程序的影响
javascript中未捕获的error会阻止掉js代码继续往下执行。但是script标签之间是没有影响的,上一个标签发生error,不会阻止下一个script的执行(行内脚本或引入脚本都是这样的)。
一. SyntaxError 语法错误。
var a = { var b = 2; } // SyntaxError
var a; // SyntaxError 后面是中文分号
var json = "{'name':'liyanfeng'}";
var obj = JSON.parse(json); // SyntaxError: Unexpected token ' in JSON at position 1(…)
2016-10-07更新
使用const
定义常量但未初始化,也是SyntaxError
var ret = typeof b;
document.write(ret);
const b;// Uncaught SyntaxError: Missing initializer in const declaration
二. TypeError 类型错误。
常发生在访问一个对象不存在的方法或在null/undefined上调用属性和方法(类似于java中的NullPointerException)。
var obj = {};
obj.map(); // TypeError: a.map is not a function(…)
var d;
d.length; // TypeError: Cannot read property 'length' of undefined
2017-4-25 更新
TypeError: Cannot convert undefined or null to object
1. Object.keys(null)
2. delete null[0]
> 2017-5-24 更新
TypeError: Cannot match against 'undefined' or 'null'.
1. var {id} = null
三. ReferenceError 引用错误。
常发生在把一个未声明的变量赋值给另外一个变量
var a = undefinedVariable; // ReferenceError: undefinedVariable is not defined(…)
或访问一个不存在的变量
console.log(age) // Uncaught ReferenceError: age is not defined(…)
2016-10-07更新
const
和let
的出现使得typeof
操作符不再百分百安全。也会抛出ReferenceError
这种情况称之为暂时性死区 (TDZ, Temporal Dead Zone)
var ret = typeof b;
document.write(ret); // Uncaught ReferenceError: b is not defined
let b; // const b = xx;
相关文章: http://tonghuashuo.github.io/blog/es6-daily-02-let-and-const.html
四. URIError URI错误。
decodeURI("%");// URIError: URI malformed(…)
decodeURIComponent("%") // URIError: URI malformed(…)
// 奇怪的是,unescape("%") 却不会引发错误
unescape("%");// %
五. RangeError 用来自定义范围错误。
var min = 0, max = 400, check = function(num) {
if (num < min || num > max) {
throw new RangeError('Parameter must be between ' + min + ' and ' + max);
}
};
try {
check(500);
} catch (e) {
if (e instanceof RangeError) {
// Handle range error
throw e;
}
}
try {
check(300);
} catch (e) {
if (e instanceof RangeError) {
throw e;
}
}
六. onerror
onerror 能捕获所有的异常
1、SyntaxError 2、runtime error 3、throw error