【问题标题】:Javascript ES5/ES6 classes and error handlingJavascript ES5/ES6 类和错误处理
【发布时间】:2019-02-11 23:26:20
【问题描述】:

假设我有这样的课程

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 语句。还是每次看到错误时我都必须手动编写它。

【问题讨论】:

  • 我通常会在我的哨兵调用中添加额外的日志记录,因此我在错误中有更多数据,因为异常是无用的。你可以定义某种函数,但你基本上是在写同样的东西,只是跳过你复制和粘贴的内容。
  • 我收到的错误信息实际上非常有用。所以我不介意只记录原始错误。就我而言,它们中的大多数来自 firebase api

标签: javascript sentry mobx-react


【解决方案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
  } 
}

【讨论】:

  • 哦,这看起来很完美。
  • 其实我遇到了问题
  • 实际上我遇到了一个问题,说我有这个代码:gist.github.com/lemiesz/3bf6397716cdc4a3fe04b9fe509bb46acatchError 装饰器不再处理我从 try, catch 块抛出的异常
  • 我更新了处理异步情况的答案,它有效吗?
  • 还没有时间尝试...但看起来不错。感谢您的帮助。今天晚些时候会回复你
【解决方案2】:

您可以使用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
  }
}

【讨论】:

  • 不是我想要的。我想要的是一个可扩展的类,它可以捕获任何错误并报告它。事先不知道函数签名。
猜你喜欢
  • 2019-11-18
  • 2016-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-05
  • 1970-01-01
  • 2016-02-14
相关资源
最近更新 更多