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

使用Zod验证器与类方法时遇TypeError:无法读取formatError属性

问题分析与解决

报错 TypeError: Cannot read property 'formatError' of undefined 的核心原因是:VerifyRequestsBody 类实例化时,没有传入 FormatError 的实例,导致类内部的 this.formatError 为 undefined,调用其 convertError 方法时触发错误。

解决方法

方法1:实例化时传入 FormatError 实例

在创建 VerifyRequestsBody 实例的代码中,先初始化 FormatError,再传入构造函数:

// 示例:在注册中间件的地方
const formatError = new FormatError();
const verifyBodyMiddleware = new VerifyRequestsBody(formatError);
// 然后将 verifyBodyMiddleware.verifyBodyFigure 作为中间件使用

方法2:修改类实现,避免依赖外部传入

如果不需要依赖注入的设计,可以直接在 VerifyRequestsBody 内部初始化 FormatError,或者将 convertError 改为静态方法:

方式A:构造函数默认创建实例

export class VerifyRequestsBody implements IMiddlewaresRules {
  private formatError: FormatError;

  // 可选参数,没传则自动创建实例
  constructor(formatError?: FormatError) {
    this.formatError = formatError || new FormatError();
  }

  // 其余代码保持不变
}

方式B:将 convertError 改为静态方法

class FormatError {
  // 改为静态方法,无需实例化即可调用
  static convertError(
    err: ZodError
  ): Array<{ message: string; key: (string | number)[]; code: number }> {
    return err.issues.map((err) => ({
      message: err.message,
      key: err.path,
      code: 400,
    }));
  }
}

// 在 VerifyRequestsBody 中直接调用静态方法
export class VerifyRequestsBody implements IMiddlewaresRules {
  verifyBodyFigure(
    req: Request,
    res: Response,
    next: NextFunction
  ): Response | any {
    const { data } = req.body;

    try {
      figureBodySchema.parse(data);
    } catch (err) {
      if (err instanceof ZodError) {
        // 直接调用静态方法,无需依赖实例
        return res.status(400).json(FormatError.convertError(err));
      }
    }
    next();
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 03:05:37