Javascript ES5 / ES6类和错误处理

问题描述 投票:2回答:2

说我有这样的课程

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
         } 
    } 
}

我为每个异步函数重复该模式。如果失败,我会回复错误,然后将其报告给某个服务(在这种情况下,该服务是Sentry)。

无论如何我可以创建一个基类,它将使用Sentry.captureException()自动装饰我的catch语句。或者我每次看到错误时都必须手动编写它。

javascript sentry mobx-react
2个回答
1
投票

你可以定义一个装饰器来重用那个逻辑并装饰可以抛出的方法:

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
  } 
}

0
投票

您可以使用Sentry.captureException(e);创建基类,然后为自定义try / catch功能提供可重写的函数。

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
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.