A demo of TS decorator

const userInfo: any = undefined

class Test {
  getName() {
    return userInfo.name
  }
}

const test = new Test()
test.getName()
Copy the code

TypeError: Cannot read property ‘name’ of undefined because userInfo has no name attribute

Using a try… catch…

getName() { try { return userInfo.name; } catch (error) {console.log("name does not exist "); }}Copy the code

If there are other methods, then each of them needs to be a try… catch… The code gets really long

** Use method decorator to solve the try… catch… **

<izhaong [email protected]> * @date: 2020-09-23 11:53:53 * @lasteditors: <izhaong [email protected]> * @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 has a problem "); }}; } class Test { @catchError getName() { return userInfo.name; } } const test = new Test(); test.getName();Copy the code

Then use factory mode to accurately output information

<izhaong [email protected]> * @date: 2020-09-23 11:53:53 * @lasteditors: <izhaong [email protected]> * @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 not found ') getName() {return userinfo.name; } @catcherror (' userinfo.age does not exist ') getAge() {return userinfo.age; } } const test = new Test(); test.getName(); test.getAge();Copy the code