You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中捕获指定类型及子类的异常?

在JavaScript中捕获指定类型及子类的异常

当然可以实现类似PHP的指定类型异常捕获功能,下面是具体的实现方式:

1. 先定义自定义异常类

JavaScript中自定义异常需要继承内置的Error类,同时要修正原型链,保证instanceof判断能正常识别子类:

// 基础自定义异常类
class MyCustomException extends Error {
  constructor(message) {
    super(message);
    this.name = 'MyCustomException'; // 重写name属性,便于区分异常类型
    Object.setPrototypeOf(this, MyCustomException.prototype); // 修复原型链
  }
}

// 自定义异常子类
class MyCustomSubException extends MyCustomException {
  constructor(message) {
    super(message);
    this.name = 'MyCustomSubException';
    Object.setPrototypeOf(this, MyCustomSubException.prototype);
  }
}

// 另一个独立的自定义异常类
class AnotherCustomException extends Error {
  constructor(message) {
    super(message);
    this.name = 'AnotherCustomException';
    Object.setPrototypeOf(this, AnotherCustomException.prototype);
  }
}

2. 在catch块中过滤指定异常类型

JavaScript的catch会捕获所有异常,我们可以在块内用instanceof判断异常是否属于目标类型(包括子类):

捕获单个类型及其子类

try {
  throw new MyCustomSubException('这是自定义子类抛出的异常');
} catch (error) {
  if (error instanceof MyCustomException) {
    console.error('捕获到自定义异常:', error.message);
  } else {
    // 不属于目标类型的异常,重新抛出交给上层处理
    throw error;
  }
}

捕获多个类型及其子类

类似PHP的多类型捕获,用逻辑或||组合多个instanceof判断:

try {
  throw new AnotherCustomException('这是另一个自定义异常');
} catch (error) {
  if (error instanceof MyCustomException || error instanceof AnotherCustomException) {
    console.error('捕获到目标异常:', error.message);
  } else {
    throw error;
  }
}

封装辅助函数简化判断

如果需要频繁判断多个异常类型,可以封装一个工具函数:

function isTargetError(error, ...errorClasses) {
  return errorClasses.some(cls => error instanceof cls);
}

// 使用示例
try {
  throw new MyCustomSubException('子类异常');
} catch (error) {
  if (isTargetError(error, MyCustomException, AnotherCustomException)) {
    console.error('捕获到指定类型异常');
  } else {
    throw error;
  }
}

内容的提问来源于stack exchange,提问作者Lajos Arpad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 18:42:45