如下代码在运行时后发生错误:
const userInfo: any = undefined
class Test {
getName() {
return userInfo.name
}
getAge() {
return userInfo.age
}
}
const test = new Test()
test.getName()
在调用 tset.getName() 时,因为 userInfo.name 不存在会发生错误;通常我们需要添加防御型代码捕获异常。
const userInfo: any = undefined
class Test {
getName() {
try {
return userInfo.name
} catch (error) {
console.log('userInfo.name 不存在')
}
}
getAge() {
try {
return userInfo.age
} catch (error) {
console.log('userInfo.age 不存在')
}
}
}
const test = new Test()
test.getName()
添加了 try..catche 代码后,我们就能捕获相应的错误,但是每个方法都需要添加 try...catch.. 这样的代码,存在反复编写重复代码的问题。我们可以使用 “装饰器” 解决这个问题。
const userInfo: any = undefined;
/**
* 错误捕获装饰器
* @param msg 错误信息
* @returns
*/
function catchError(msg: string) {
return function (target: any, key: string, descriptor: PropertyDescriptor) {
const fn = descriptor.value;
descriptor.value = function () {
try {
fn();
} catch (error) {
console.log(msg);
}
};
};
}
class Test {
@catchError("userInfo.name 存在问题")
getName() {
return userInfo.name;
}
@catchError("userInfo.age 存在问题")
getAge() {
return userInfo.age;
}
}
const test = new Test();
test.getName();