You need to enable JavaScript to run this app. TypeScript NodeJS自定义catchAsync装饰器时类方法无法访问this
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript NodeJS自定义catchAsync装饰器时类方法无法访问this

异步错误捕获装饰器类方法this访问问题

编写了用于捕获异步错误的装饰器,但应用于类方法时无法正常访问this关键字。当前需求为构建可复用的CRUD基类,供其他业务类继承,直接实现通用的CRUD操作方法。

现有catchAsync装饰器代码

import { Request, Response, NextFunction } from 'express';

export function catchAsync(target: any, key: string, desc: PropertyDescriptor) {
    const method = desc.value;
    desc.value = function (req: Request, res: Response, next: NextFunction) {
        method(req, res, next).catch(next);
    }
}

可复用Controller基类代码

import { Request, Response, NextFunction } from 'express';
import { Model, Document } from 'mongoose';
import { catchAsync } from '../utils/catchAsync';

export abstract class Controller<T extends Document> {
    constructor(public Model: Model<T>) {
        this.getAll = this.getAll.bind(this);
    }

    abstract Model: Model<T>

    @catchAsync
    async getAll(req: Request, res: Response, next: NextFunction) {
        console.log('this: ', this);
        const instance = await this.Model.find();

        res.status(200).json({
            status: 'success',
            data: { [this.Model.modelName.toLowerCase()]: instance }
        });
    }
}

业务控制器类(UserController)代码

import { Request, Response, NextFunction } from 'express';
import { Controller } from './baseController';
import { User, IUser } from '../models/userModel';
import { ApiError } from '../utils/apiError';
import { catchAsync } from '../utils/catchAsync';
import { Model } from 'mongoose';

export class UserController extends Controller<IUser> {
    Model = User;

    @catchAsync
    async getUser(req: Request, res: Response, next: NextFunction) {
        const users = await User.find();
        console.log('users: ', users);
        throw new Error('Game of error');
        
        res.send('User Routes');
    }
}

控制台输出结果

控制台输出截图


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.27 11:54:04