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

TypeScript中如何给继承Error的自定义错误类添加额外属性

解决方案

1. 修改自定义错误类定义,新增自定义属性的类型声明和赋值逻辑

比如你要新增errorCode(业务错误码)和details(额外详情)两个自定义属性,修改后的类代码如下:

export class ApiError extends Error {
  status: number;
  // 新增自定义属性的类型声明
  errorCode?: string;
  details?: Record<string, any>;

  // 构造函数新增可选的自定义参数,放在最后避免影响原有调用逻辑
  constructor(status: number, msg: string, errorCode?: string, details?: Record<string, any>) {
    super(msg);
    Error.captureStackTrace(this, this.constructor);
    this.status = status;
    // 给自定义属性赋值
    if (errorCode) this.errorCode = errorCode;
    if (details) this.details = details;
  }
}

如果你想要更灵活的通用配置,也可以直接加一个通用的meta字段存储所有自定义内容:

export class ApiError extends Error {
  status: number;
  meta?: Record<string, any>;

  constructor(status: number, msg: string, meta?: Record<string, any>) {
    super(msg);
    Error.captureStackTrace(this, this.constructor);
    this.status = status;
    if (meta) this.meta = meta;
  }
}

2. 实例化错误类时传入自定义属性值

比如抛出用户不存在的错误时:

// 单属性定义写法
throw new ApiError(404, "User wasn't found", "USER_NOT_FOUND", { userId: 123 })

// 通用meta写法
throw new ApiError(404, "User wasn't found", { errorCode: "USER_NOT_FOUND", userId: 123 })

3. 调整全局错误处理中间件

Express、Koa等框架的默认错误处理只会返回status和message,你需要手动修改全局错误处理中间件,把自定义属性也加入响应体,以Express为例:

app.use((err: ApiError, req: Request, res: Response, next: NextFunction) => {
  const status = err.status || 500
  res.status(status).json({
    message: err.message,
    status: status,
    // 新增你要返回的自定义属性
    errorCode: err.errorCode,
    details: err.details
    // 如果是meta写法直接展开即可:...err.meta
  })
})

完成以上操作后前端收到的响应结构就会包含你新增的自定义属性:

data: {
   message: "User wasn't found",
   status: 404,
   errorCode: "USER_NOT_FOUND",
   details: { "userId": 123 }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 20:06:00