首页 > 解决方案 > 如何访问打字稿中方法的所有参数?

问题描述

我已经构建了一个装饰器来处理我的服务中的某个错误。我是这样实现的:

interface MyServiceInterface {
    doBar(otherParam: number): string;

    doFoo(param1: string, param2: number): string;
}

class MyServiceClass implements MyServiceInterface {

    doFoo(param1: string, param2: number): string {
        throw new Error("I SHOULD BE CAUGHT");
    }

    doBar(otherParam: number): string {
        throw new Error("I SHOULD BE CAUGHT");
    }
}

class MyDecorator implements MyServiceInterface {
    constructor(private service: MyServiceInterface) {
    }

    public doFoo(param1: string, param2: number): string {
        try {
            return this.service.doFoo(param1, param2);
        } catch (e) {
            return "THIS SPECIAL CASE IS NOW RESOLVED";
        }
    }

    public doBar(otherParam: number): string {
        try {
            return this.service.doBar(otherParam);
        } catch (e) {
            return "THIS SPECIAL CASE IS NOW RESOLVED";
        }
    }
}

const instance = new MyDecorator(new MyServiceClass());

console.log([
    instance.doBar(1),
    instance.doFoo("biz", 2),
].join("\n"));

我不喜欢在装饰器中重复自己,因此我希望我的 catch 块更有活力。我想将函数和所有参数传递到一个函数中,因为我的错误处理将是相同的。

我怎样才能做到这一点?

标签: node.jstypescriptoopdecorator

解决方案


您可以将函数存储为变量并将参数存储在数组中。然后你可以function.apply像这样使用:

class MyDecorator implements MyServiceInterface {
    constructor(private service: MyServiceInterface) {
    }

    public doFoo(param1: string, param2: number): string {
        const args = [param1, param2];

        return this.handleErrorCase(this.service.doFoo, args);
    }

    public doBar(otherParam: number): string {
        const args = [otherParam];

        return this.handleErrorCase(this.service.doBar, args);
    }

    private handleErrorCase<T>(fn: any, args: any[]): string {
        try {
            return fn.apply(this.service, args) as string;
        } catch (e) {
            return "THIS SPECIAL CASE IS NOW RESOLVED";
        }

    }
}

推荐阅读