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
相关产品推荐
相关产品推荐

