广州总部电话:020-85564311
广州总部电话:020-85564311
20年
互联网应用服务商
请输入搜索关键词
知识库 知识库

优网知识库

探索行业前沿,共享知识宝库

JavaScript 内置错误类型详解

发布日期:2025-08-08 17:59:34 浏览次数: 810 来源:前端小刷
推荐语
掌握JavaScript错误处理的关键,从基础Error到高级AggregateError,让你的代码更健壮。

核心内容:
1. JavaScript错误对象的基础用法与自定义错误类
2. 常见内置错误类型的特点与使用场景
3. 实际开发中的错误处理最佳实践
小优 网站建设顾问
专业来源于二十年的积累,用心让我们做到更好!

这篇文章主要详细介绍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的错误对象体系提供了强大的错误处理能力。通过合理使用不同类型的错误对象,我们可以:

  1. 精确识别错误类型:根据不同的错误类型采取相应的处理策略
  2. 提供详细的错误信息:帮助开发者快速定位和解决问题
  3. 实现优雅的错误处理:避免程序崩溃,提供更好的用户体验
  4. 支持自定义错误:根据业务需求创建专门的错误类型

掌握这些错误对象的使用方法,将大大提升JavaScript代码的健壮性和可维护性。在实际开发中,建议根据具体场景选择合适的错误类型,并建立统一的错误处理机制。

优网科技,优秀企业首选的互联网供应服务商

优网科技秉承"专业团队、品质服务" 的经营理念,诚信务实的服务了近万家客户,成为众多世界500强、集团和上市公司的长期合作伙伴!

优网科技成立于2001年,擅长网站建设、网站与各类业务系统深度整合,致力于提供完善的企业互联网解决方案。优网科技提供PC端网站建设(品牌展示型、官方门户型、营销商务型、电子商务型、信息门户型、微信小程序定制开发、移动端应用(手机站APP开发)、微信定制开发(微信官网、微信商城、企业微信)等一系列互联网应用服务。


我要投稿

姓名

文章链接

提交即表示你已阅读并同意《个人信息保护声明》

专属顾问 专属顾问
扫码咨询您的优网专属顾问!
专属顾问
马上咨询
联系专属顾问
联系专属顾问
联系专属顾问
扫一扫马上咨询
扫一扫马上咨询

扫一扫马上咨询

和我们在线交谈!