这篇文章主要详细介绍JavaScript中所有内置的错误对象类型,包括它们的特点、使用场景和实际应用示例。
JavaScript中的错误对象是处理异常情况的重要工具。它们不仅帮助我们捕获和处理程序中的错误,还能提供详细的错误信息,便于调试和问题定位。
错误对象基础
Error 基类
Error
是所有错误对象的基类,它提供了错误处理的基本功能。Error
可以理解就是一个普通的 JavaScript 构造函数,当代码运行时发生错误,会创建新的 Error
对象,并将其抛出(throw
)。
基本用法
const error = new Error('这是一个错误信息');
console.log(error.message); // "这是一个错误信息"
console.log(error.name); // "Error"
console.log(error.stack);
/**
Error: 这是一个错误信息
at <anonymous>:1:15
**/
自定义错误类
// 自定义错误类
class CustomError extends Error {
constructor(message, code) {
super(message);
this.name = 'CustomError';
this.code = code;
}
}
const customError = new CustomError('自定义错误', 'CUSTOM_001');
console.log(customError.name); // "CustomError"
console.log(customError.code); // "CUSTOM_001"
错误处理例子
function doSomething(callback) {
try {
if (typeof callback !== 'function') {
throw new Error(callback + ' is not a function');
}
// ...
callback()
} catch (error) {
console.error('发生错误:', error.message);
return null;
}
}
doSomething(2) // 发生错误: 2 is not a function
具体错误类型详解
1. AggregateError - 聚合错误
AggregateError
用于表示多个错误组合的情况,特别适用于Promise.all()等并发操作。
基本用法
const errors = [
new Error('第一个错误'),
new Error('第二个错误'),
new Error('第三个错误')
];
const aggregateError = new AggregateError(errors, '多个操作失败');
console.log(aggregateError.name); // "AggregateError"
console.log(aggregateError.message); // "多个操作失败"
console.log(aggregateError.errors);
/**
(3) [Error: 第一个错误
at <anonymous>:2:3, Error: 第二个错误
at <anonymous>:3:3, Error: 第三个错误
at <anonymous>:4:3]
**/
实际应用例子
async function processMultipleTasks() {
const tasks = [
fetch('https://api1.qdxs.com'),
fetch('https://api2.qdxs.com'),
fetch('https://api3.qdxs.com')
];
try {
const results = await Promise.allSettled(tasks);
const errors = results
.filter(result => result.status === 'rejected')
.map(result => result.reason);
if (errors.length > 0) {
throw new AggregateError(errors, '部分API调用失败');
}
return results.map(result => result.value);
} catch (error) {
if (error instanceof AggregateError) {
console.error('聚合错误:', error.message);
error.errors.forEach((err, index) => {
console.error(`错误 ${index + 1}:`, err.message);
});
}
throw error;
}
}
2. EvalError
EvalError
表示与eval()
函数相关的错误,不过它不再会被 JavaScript 抛出,不过该对象仍然存在。
try {
eval('const x = 1; let x = 2;'); // 重复声明
} catch (error) {
console.error('EvalError:', error.message);
}
// SyntaxError: Identifier 'x' has already been declared
上面代码中,虽然执行 eval
发生了错误,但是抛出的错误并不是 EvalError
类型,而是 SyntaxError
,足以证明它不再会被 JavaScript 抛出。
3. RangeError - 范围错误
RangeError
表示数值超出有效范围时抛出的错误。
// 数组长度超出范围
try {
const arr = new Array(-1); // 负数长度
} catch (error) {
console.log(error instanceof RangeError); // true
console.log(error.message); // "Invalid array length"
}
4. ReferenceError - 引用错误
ReferenceError
表示访问未定义的变量或对象属性时抛出的错误。
// 访问未定义的变量
try {
console.log(qdxs);
} catch (error) {
console.log(error instanceof ReferenceError); // true
console.log(error.message); // "qdxs is not defined"
}
5. SyntaxError - 语法错误
SyntaxError
表示JavaScript代码语法错误。
// 基本语法错误
try {
const x = 1;
const x = 2; // 重复声明
} catch (error) {
console.log(error instanceof SyntaxError); // true
console.log(error.message); // "Identifier 'x' has already been declared"
}
6. TypeError - 类型错误
TypeError
表示操作的类型不正确时抛出的错误。
// 调用非函数
try {
const notAFunction = 123;
notAFunction();
} catch (error) {
console.log(error instanceof TypeError); // true
console.log(error.message); // "notAFunction is not a function"
}
7. URIError - URI错误
URIError
表示URI编码或解码错误。
// 解码错误
try {
decodeURIComponent('%'); // 不完整的编码
} catch (error) {
console.log(error instanceof URIError); // true
console.log(error.message); // "URI malformed"
}
总结
JavaScript的错误对象体系提供了强大的错误处理能力。通过合理使用不同类型的错误对象,我们可以:
精确识别错误类型:根据不同的错误类型采取相应的处理策略 提供详细的错误信息:帮助开发者快速定位和解决问题 实现优雅的错误处理:避免程序崩溃,提供更好的用户体验 支持自定义错误:根据业务需求创建专门的错误类型
掌握这些错误对象的使用方法,将大大提升JavaScript代码的健壮性和可维护性。在实际开发中,建议根据具体场景选择合适的错误类型,并建立统一的错误处理机制。

優(yōu)網(wǎng)科技秉承"專業(yè)團(tuán)隊、品質(zhì)服務(wù)" 的經(jīng)營理念,誠信務(wù)實(shí)的服務(wù)了近萬家客戶,成為眾多世界500強(qiáng)、集團(tuán)和上市公司的長期合作伙伴!
優(yōu)網(wǎng)科技成立于2001年,擅長網(wǎng)站建設(shè)、網(wǎng)站與各類業(yè)務(wù)系統(tǒng)深度整合,致力于提供完善的企業(yè)互聯(lián)網(wǎng)解決方案。優(yōu)網(wǎng)科技提供PC端網(wǎng)站建設(shè)(品牌展示型、官方門戶型、營銷商務(wù)型、電子商務(wù)型、信息門戶型、微信小程序定制開發(fā)、移動端應(yīng)用(手機(jī)站、APP開發(fā))、微信定制開發(fā)(微信官網(wǎng)、微信商城、企業(yè)微信)等一系列互聯(lián)網(wǎng)應(yīng)用服務(wù)。