当像函数一样使用 Error 时, 如果没有 new , 它将返回一个 Error 对象. 所以, 仅仅调用 Error 产生的结果与通过 new 关键字构造 Error 对象生成的结果相同.
1 2 3
// this: const x = Error('I was created using a function call!'); // has the same functionality as this: const y = newError('I was constructed via the "new" keyword!');
ReferenceError: 引用的变量不存在
1
console.log(a) // ReferenceError: a is not defined
TypeError: 数据类型不正确的错误
1 2
let b console.log(b.xxx) // TypeError: Cannot read property 'xxx' of undefined
1 2
let b = {} b.xxx() // TypeError: b.xxx is not a function
RangeError: 数据值不在其所允许的范围内
1 2 3 4 5
functionfun () { fun() }
fun() // RangeError: Maximum call stack size exceeded
SyntaxError: 语法错误
1
let c = ''''// SyntaxError: Unexpected string
Error 的处理
捕获错误: try…catch
1 2 3 4 5
try { console.log(a) } catch(err) { console.log(err) // ReferenceError: a is not defined }
抛出错误: throw Error
1
thrownewError('哎呀, 出错啦!!!')
Error 属性
message: 错误相关信息
1 2 3 4 5
try { console.log(a) } catch(err) { console.log(err.message) // a is not defined }
stack: 函数调用栈记录信息
1 2 3 4 5
try { console.log(a) } catch(err) { console.log(err.stack) // ReferenceError: a is not defined at <anonymous>:2:15 }