如何在打字稿中编写错误处理装饰器

Alb*_*ert 7 typescript

控制器的方法之一如下所示:

@httpGet('')
public async getProducts(@queryParam() queryBody: object): Promise<Products[]> {
    return this.productService.getProducts(queryBody);
}
Run Code Online (Sandbox Code Playgroud)

我想要一个装饰器,可以@Catch()在该方法上使用(如果像这样调用那么它应该是一个装饰器工厂),它的职责是捕获来自服务方法的错误/异常。我只是想将错误处理逻辑与控制器中的逻辑解耦。

Tow*_*iff 10

创建一个将作为装饰器的函数catchError,并在该函数中使用包装函数更改现有函数。您可以bar通过 访问现有功能descriptor.value

存在一个问题,返回类型可以从catchError函数中更改,并且在打字稿中不可见。

class Foo {
    @catchError
    public bar(message: string): string {
        if(message === "x") {
            throw new Error("x not valid");
        }

        return message;
    }
}

function catchError(target: any,propertyName: any,descriptor: any) {
    const method = descriptor.value;

    descriptor.value = function(...args: any) {
        try {
            return method.apply(target, args);
        } catch(error) {
            throw new Error(`Special error message: ${error.message}`);
        }
    };
}

const foo = new Foo();
const result = foo.bar("x");

console.log(result);
Run Code Online (Sandbox Code Playgroud)