前端避免一直try...catch...(ts装饰器)

​一个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();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值