简体   繁体   English

Javascript ES5/ES6 类和错误处理

[英]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).在失败时,我会响应错误,然后将其报告给某个服务(在这种情况下,该服务是 Sentry)。

Is there anyway I can create a BaseClass, that will automatically decorate my catch statement with Sentry.caputreException().无论如何我可以创建一个BaseClass,它会自动用Sentry.caputreException()装饰我的catch语句。 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);您可以使用Sentry.captureException(e);创建一个基类Sentry.captureException(e); , and then have overrideable functions for the custom try/catch functionality. ,然后为自定义 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
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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