JavaScript 中的错误类型大致可以分为以下几类:
- SyntaxError
- ReferenceError
- TypeError
- RangeError
- EvalError
- URIError
- AggregateError
下面我们将详细解释每种错误类型,并通过代码示例展示这些错误是如何产生的。
1. SyntaxError
SyntaxError 是由于代码的语法不正确而引发的错误。
// 代码示例:缺少括号
try {
eval('var a = 1 + 2;'); // 正确的语法
eval('var a = 1 + 2'); // 缺少分号,语法错误
} catch (e) {
console.error(e.name + ': ' + e.message); // SyntaxError: Unexpected end of input
}
2. ReferenceError
ReferenceError 是由于引用了不存在的变量而引发的错误。
// 代码示例:引用未定义的变量
try {
console.log(nonExistentVariable); // nonExistentVariable 未定义
} catch (e) {
console.error(e.name + ': ' + e.message); // ReferenceError: nonExistentVariable is not defined
}
3. TypeError
TypeError 是由于操作数或参数的类型不正确而引发的错误。
// 代码示例:对非函数类型调用函数
try {
var num = 42;
num(); // num 不是函数
} catch (e) {
console.error(e.name + ': ' + e.message); // TypeError: num is not a function
}
4. RangeError
RangeError 是由于数值超出允许范围而引发的错误。
// 代码示例:数组长度超出范围
try {
var arr = new Array(-1); // 数组长度不能为负数
} catch (e) {
console.error(e.name + ': ' + e.message); // RangeError: Invalid array length
}
5. EvalError
EvalError 是由于 eval() 函数的错误使用而引发的错误。现代 JavaScript 中很少会遇到这个错误,因为 eval() 的使用已经被强烈不推荐。
// 代码示例:错误使用 eval
try {
eval('foo bar'); // 语法错误
} catch (e) {
console.error(e.name + ': ' + e.message); // SyntaxError: Unexpected identifier
// 现代 JavaScript 中,EvalError 很少被抛出
}
6. URIError
URIError 是由于 encodeURI() 或 decodeURI() 函数的错误使用而引发的错误。
// 代码示例:错误使用 decodeURI
try {
decodeURI('%'); // '%' 是无效的 URI 组件
} catch (e) {
console.error(e.name + ': ' + e.message); // URIError: URI malformed
}
7. AggregateError
AggregateError 是 ES2021 引入的,用于表示一个操作有多个错误的情况,通常与 Promise.allSettled() 或 Promise.any() 一起使用。
// 代码示例:Promise.any() 产生 AggregateError
Promise.any([
Promise.reject(new Error('Error 1')),
Promise.reject(new Error('Error 2')),
Promise.resolve('Success')
])
.then(console.log)
.catch(e => {
if (e instanceof AggregateError) {
console.error(e.name + ': ' + e.message); // AggregateError: All promises were rejected
e.errors.forEach(error => console.error(error));
}
});
总结
以上是 JavaScript 中常见的错误类型及其产生原因的详细解释。了解这些错误类型有助于在开发过程中更好地调试和处理异常情况。