简体   繁体   中英

Javascript ES5/ES6 classes and error handling

Say I have a class like this

class SomeUIComponentDataStore {
    async function getUser() {
         try { //do something that can fail}
         catch(e) { 
           // gracefully fail, setting portion of ui to fail state
           Sentry.captureException(e); // report to some metrics service
         } 
    } 
}

I repeat that pattern for every async function. Where on failure I respond to the error, and then report it to some service (in this case that service is Sentry).

Is there anyway I can create a BaseClass, that will automatically decorate my catch statement with Sentry.caputreException(). Or do i have to manually write it each time a I see an error.

You could define a decorator to reuse that logic and decorate methods that can throw:

function catchError(target, name, descriptor) {
  const original = descriptor.value;
  if (typeof original === 'function') {
    descriptor.value = function(...args) {
      try {
        return original.apply(this, args);
      } catch (e) {
        Sentry.captureException(e); // report to some metrics service
      }
    }
  }
}

function catchErrorAsync(target, name, descriptor) {
  const original = descriptor.value;
  if (typeof original === 'function') {
    descriptor.value = async function(...args) {
      try {
        return await original.apply(this, args);
      } catch (e) {
        Sentry.captureException(e); // report to some metrics service
      }
    }
  }
}

class SomeUIComponentDataStore {
  @catchErrorAsync
  async getUser() {
    //do something that can fail
  }

  @catchError
  otherMethod() {
    //do something that can fail
  } 
}

You could create a base class with the Sentry.captureException(e); , and then have overrideable functions for the custom try/catch functionality.

class BaseClass {
  function onGetUser() {
    throw new Error("Method not implemented");
  }

  function onGetUserFail() {
    throw new Error("Method not implemented");
  }

  async function getUser() {
    try {
      onGetUser();
    } catch (e) {
      onGetUserFail();
      Sentry.captureException(e);
    }
  }
}

class SomeUIComponentDataStore extends BaseClass {
  function onGetUser() {
    // do something
  }

  function onGetUserFail() {
    // do something
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM