防止 Sentry.io 记录服务器错误代码

Fra*_*sco 4 logging sentry angular

我有一个使用 Sentry.io 进行日志记录的 Angular 应用程序。我创建了一个自定义错误处理程序类,在其中初始化 Sentry,并且希望避免日志服务器错误(404 未找到或 500 服务器错误)。

我读到,如果 Angular 中的网络调用失败,异常会冒泡,并且不会在 ErrorHandler 中捕获(因此它不会触发handleError方法)。

然而,即使我使用该beforeSend()方法,按照建议面对这种非常特殊的情况,控制台日志也会被写入(例如SENTRY SKIPPING EVENT),但所有服务器错误都会记录在Sentry中。

export class MyhErrorHandler implements ErrorHandler {

    if (environment.production) {

      Sentry.init({
        dsn: 'https://12314567@sentry.io/123456789',
        environment: this.environmentData.env,
        beforeSend(event) {
          try {
            if (this.isServerError(JSON.stringify(event))) {
              console.log('------   SENTRY SKIPPING EVENT: ', {event});
              return null;
            }
          } catch (e) {
            console.log('------   SENTRY ERROR: ', {e});
          }
          return event;
        }
      });
    }

   handleError(err: any): void {
     if (!this.isServerError(err)) {    
       const errorText = MyhErrorHandler.getError(err);
       Sentry.captureException(errorText);
     }
   }

  private isServerError(error: any): boolean {
    if (!error) {
      return false;
    }

    const regex = new RegExp(
      `500 Internal Server Error|401 Unauthorized|403 Forbidden|404 Not Found|502 Bad Gateway|503 Service Unavailable`,
      'mi'
    );

      return regex.test(JSON.stringify(error);
    } catch (error) {
      Sentry.captureException(`Error in myh-error-handler while parsing error Obj: ${errorText} -- ${error.message}`);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Fra*_*sco 8

我找到了解决问题的方法,并将其写在这里,以便对其他人有所帮助。

ignoreErrors我在 Sentry 初始化期间使用了接受字符串或正则表达式的属性:

const serverErrorsRegex = new RegExp(
      `500 Internal Server Error|401 Unauthorized|403 Forbidden|404 Not Found|502 Bad Gateway|503 Service Unavailable`,
      'mi'
    );

 Sentry.init({
        dsn: 'https://123456@sentry.io/12345678',
        environment: this.environmentData.env,

        // We ignore Server Errors. We have to define here since Angular 
        // http client uses setTimeout to detect http call progress.
        // And when the call fails, it throws an exception inside that timeout 
        // that bubbles up higher to the main Angular's error handler.
        ignoreErrors: [serverErrorsRegex]
      });
Run Code Online (Sandbox Code Playgroud)

在正则表达式中,我使用了代表以下含义的标志mi

  • 'm':多行模式
  • 'i':不区分大小写

有关正则表达式标志的更多详细信息请参见此处。