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

如何提取console.log打印对象的类型名称(如SigninError)

提取Error对象的类名"SigninError"的方法

嘿,要从你的SigninError实例里提取这个类名字符串,有两个实用的方法可以试试:

  • 方法一:直接使用constructor.name
    这是最简洁的方式,每个对象的constructor属性指向它的构造函数,而构造函数的name属性就是类的名称。直接调用即可:
const errorClassName = error.constructor.name;
console.log(errorClassName); // 输出 "SigninError"
  • 方法二:通过Object.prototype.toString配合字符串截取
    如果遇到特殊场景(比如代码被压缩导致constructor.name失效),可以用这个更鲁棒的方式:Object.prototype.toString.call(error)会返回格式为"[object SigninError]"的字符串,我们只需要截取中间的类名部分:
const className = Object.prototype.toString.call(error).slice(8, -1);
console.log(className); // 输出 "SigninError"

举个完整的例子验证一下:

// 模拟你的自定义Error类
class SigninError extends Error {
  constructor(id, description) {
    super();
    this.id = id;
    this.description = description;
  }
}

// 创建实例
const error = new SigninError("el-20003", "");

// 测试两种方法
console.log(error.constructor.name); // "SigninError"
console.log(Object.prototype.toString.call(error).slice(8, -1)); // "SigninError"

一般情况下第一种方法就足够用了,简单直接;第二种方法可以作为兜底方案。

内容的提问来源于stack exchange,提问作者I. Ahmed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:15:20