首页 > 解决方案 > Javascript ES5/ES6 类和错误处理

问题描述

说我有这样的课

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)。

无论如何我可以创建一个 BaseClass,它会自动用 Sentry.caputreException() 装饰我的 catch 语句。还是每次看到错误时我都必须手动编写它。

标签: javascriptsentrymobx-react

解决方案


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

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

推荐阅读