一个ts装饰器的demo
const userInfo: any = undefined
class Test {
getName() {
return userInfo.name
}
}
const test = new Test()
test.getName()
因为userInfo中没有name属性, 会报错TypeError: Cannot read property 'name' of undefined
使用try...catch...
getName() {
try {
return userInfo.name;
} catch (error) {
console.log("name 不存在");
}
}
如果还有其他方法那么每个都需要写 try...catch...代码变得很长
**用方法装饰器解决try...catch...**
/*
* @Description: 装饰器demo
* @Author: 仲灏<izhaong 164165005@qq.com>
* @Date: 2020-09-23 11:53:53
* @LastEditors: 仲灏<izhaong 164165005@qq.com>
* @LastEditTime: 2020-09-23 17:18:57
*/
const userInfo: any = undefined;
function catchError(target: any, key: string, descriptor: PropertyDescriptor) {
const fn = descriptor.value;
descriptor.value = function () {
try {
fn();
} catch (error) {
console.log("userInfo 有问题");
}
};
}
class Test {
@catchError
getName() {
return userInfo.name;
}
}
const test = new Test();
test.getName();
再使用工厂模式,准确输出信息
/*
* @Description: 装饰器demo
* @Author: 仲灏<izhaong 164165005@qq.com>
* @Date: 2020-09-23 11:53:53
* @LastEditors: 仲灏<izhaong 164165005@qq.com>
* @LastEditTime: 2020-09-23 17:22:23
*/
const userInfo: any = undefined;
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();
test.getAge();