Создайте функцию, которая будет декоратором 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);