将 catch 捕获到的错误封装到装饰器里:

    1. const userInfo: any = undefined;
    2. function catchError(msg: string) {
    3. return function (target: any, key: string, descriptor: PropertyDescriptor) {
    4. const fn = descriptor.value;
    5. descriptor.value = function () {
    6. try {
    7. fn();
    8. } catch (e) {
    9. console.log(msg);
    10. }
    11. };
    12. };
    13. }
    14. class Test {
    15. @catchError("userInfo.name 不存在")
    16. getName() {
    17. return userInfo.name;
    18. }
    19. @catchError("userInfo.age 不存在")
    20. getAge() {
    21. return userInfo.age;
    22. }
    23. }
    24. const test = new Test();
    25. test.getName();
    26. test.getAge();