node.js - 如何访问打字稿中方法的所有参数?
问题描述
我已经构建了一个装饰器来处理我的服务中的某个错误。我是这样实现的:
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 块更有活力。我想将函数和所有参数传递到一个函数中,因为我的错误处理将是相同的。
我怎样才能做到这一点?
解决方案
您可以将函数存储为变量并将参数存储在数组中。然后你可以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";
}
}
}
推荐阅读
- jquery - Jquery,将输入数据传递给数组
- android - 颤振 | 边框半径不适用于 Android
- apache-spark - Spark 内部结构:项目的好处
- laravel-5 - 我如何在表单提交时将员工表 ID(自动递增)提交到员工 ID 下的用户表
- java - 从另一个类更新摆动组件
- android - Firebase设置值将错误的键放在已发布的应用程序上
- scala - 使一个 SBT 子项目任务依赖于另一个子项目任务
- r - 在维护顺序的同时聚合和折叠基于向量
- git - 在桌面目录下做 git init 有什么坏处?
- android - 在Android中,当应用程序处于运行或关闭状态时,是否有适当的方法来检测用户是否添加或删除了指纹?