前端避免一直try...catch...(ts装饰器)
一个ts装饰器的demo
const userInfo: any = undefined
class Test {
getName() {
return userInfo.name
}
}
const test = new Test()
test.getName()
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
因为userInfo
中没有name
属性, 会报错TypeError: Cannot read property 'name' of undefined
使用try...catch...
getName() {
try {
return userInfo.name;
} catch (error) {
console.log("name 不存在");
}
}
1
2
3
4
5
6
7
2
3
4
5
6
7
如果还有其他方法那么每个都需要写 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();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
再使用工厂模式,准确输出信息
/*
* @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();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
上次更新: 2023/09/17, 20:06:58