How to use the @sentry/utils.SyncPromise function in @sentry/utils

To help you get started, we’ve selected a few @sentry/utils examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github getsentry / sentry-javascript / packages / node / src / parsers.ts View on Github external
function readSourceFiles(filenames: string[]): PromiseLike<{ [key: string]: string | null }> {
  // we're relying on filenames being de-duped already
  if (filenames.length === 0) {
    return SyncPromise.resolve({});
  }

  return new SyncPromise<{
    [key: string]: string | null;
  }>(resolve => {
    const sourceFiles: {
      [key: string]: string | null;
    } = {};

    let count = 0;
    // tslint:disable-next-line:prefer-for-of
    for (let i = 0; i < filenames.length; i++) {
      const filename = filenames[i];

      const cache = FILE_CONTENT_CACHE.get(filename);
      // We have a cache hit
      if (cache !== undefined) {
        // If it's not null (which means we found a file and have a content)
        // we set the content and return it later.
github getsentry / sentry-javascript / packages / core / src / baseclient.ts View on Github external
protected _processEvent(event: Event, hint?: EventHint, scope?: Scope): PromiseLike {
    const { beforeSend, sampleRate } = this.getOptions();

    if (!this._isEnabled()) {
      return SyncPromise.reject('SDK not enabled, will not send event.');
    }

    // 1.0 === 100% events are sent
    // 0.0 === 0% events are sent
    if (typeof sampleRate === 'number' && Math.random() > sampleRate) {
      return SyncPromise.reject('This event has been sampled, will not send event.');
    }

    return new SyncPromise((resolve, reject) => {
      this._prepareEvent(event, scope, hint)
        .then(prepared => {
          if (prepared === null) {
            reject('An event processor returned null, will not send event.');
            return;
          }

          let finalEvent: Event | null = prepared;

          try {
            const isInternalException = hint && hint.data && (hint.data as { [key: string]: any }).__sentry__ === true;
            if (isInternalException || !beforeSend) {
              this._getBackend().sendEvent(finalEvent);
              resolve(finalEvent);
              return;
            }
github getsentry / sentry-javascript / packages / browser / src / transports / fetch.ts View on Github external
const defaultOptions: RequestInit = {
      body: JSON.stringify(event),
      method: 'POST',
      // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default
      // https://caniuse.com/#feat=referrer-policy
      // It doesn't. And it throw exception instead of ignoring this parameter...
      // REF: https://github.com/getsentry/raven-js/issues/1233
      referrerPolicy: (supportsReferrerPolicy() ? 'origin' : '') as ReferrerPolicy,
    };

    if (this.options.headers !== undefined) {
      defaultOptions.headers = this.options.headers;
    }

    return this._buffer.add(
      new SyncPromise((resolve, reject) => {
        global
          .fetch(this.url, defaultOptions)
          .then(response => {
            const status = Status.fromHttpCode(response.status);

            if (status === Status.Success) {
              resolve({ status });
              return;
            }

            if (status === Status.RateLimit) {
              const now = Date.now();
              this._disabledUntil = new Date(now + parseRetryAfterHeader(now, response.headers.get('Retry-After')));
              logger.warn(`Too many requests, backing off till: ${this._disabledUntil}`);
            }
github getsentry / sentry-javascript / packages / node / src / backend.ts View on Github external
getCurrentHub().configureScope(scope => {
          scope.setExtra('__serialized__', normalizeToSize(exception as {}));
        });

        ex = (hint && hint.syntheticException) || new Error(message);
        (ex as Error).message = message;
      } else {
        // This handles when someone does: `throw "something awesome";`
        // We use synthesized Error here so we can extract a (rough) stack trace.
        ex = (hint && hint.syntheticException) || new Error(exception as string);
      }
      mechanism.synthetic = true;
    }

    return new SyncPromise((resolve, reject) =>
      parseError(ex as Error, this._options)
        .then(event => {
          addExceptionTypeValue(event, undefined, undefined);
          addExceptionMechanism(event, mechanism);

          resolve({
            ...event,
            event_id: hint && hint.event_id,
          });
        })
        .then(null, reject),
    );
  }
github getsentry / sentry-javascript / packages / node / src / parsers.ts View on Github external
function addPrePostContext(
  filesToRead: string[],
  frames: StackFrame[],
  linesOfContext: number,
): PromiseLike {
  return new SyncPromise(resolve =>
    readSourceFiles(filesToRead).then(sourceFiles => {
      const result = frames.map(frame => {
        if (frame.filename && sourceFiles[frame.filename]) {
          try {
            const lines = (sourceFiles[frame.filename] as string).split('\n');

            frame.pre_context = lines
              .slice(Math.max(0, (frame.lineno || 0) - (linesOfContext + 1)), (frame.lineno || 0) - 1)
              .map((line: string) => snipLine(line, 0));

            frame.context_line = snipLine(lines[(frame.lineno || 0) - 1], frame.colno || 0);

            frame.post_context = lines
              .slice(frame.lineno || 0, (frame.lineno || 0) + linesOfContext)
              .map((line: string) => snipLine(line, 0));
          } catch (e) {
github getsentry / sentry-javascript / packages / node / src / backend.ts View on Github external
public eventFromMessage(message: string, level: Severity = Severity.Info, hint?: EventHint): PromiseLike {
    const event: Event = {
      event_id: hint && hint.event_id,
      level,
      message,
    };

    return new SyncPromise(resolve => {
      if (this._options.attachStacktrace && hint && hint.syntheticException) {
        const stack = hint.syntheticException ? extractStackFromError(hint.syntheticException) : [];
        parseStack(stack, this._options)
          .then(frames => {
            event.stacktrace = {
              frames: prepareFramesForEvent(frames),
            };
            resolve(event);
          })
          .then(null, () => {
            resolve(event);
          });
      } else {
        resolve(event);
      }
    });
github getsentry / sentry-javascript / packages / node / src / parsers.ts View on Github external
export function parseError(error: ExtendedError, options?: NodeOptions): PromiseLike {
  return new SyncPromise(resolve =>
    getExceptionFromError(error, options).then((exception: Exception) => {
      resolve({
        exception: {
          values: [exception],
        },
      });
    }),
  );
}
github getsentry / sentry-javascript / packages / core / src / baseclient.ts View on Github external
protected _isClientProcessing(timeout?: number): PromiseLike<{ ready: boolean; interval: number }> {
    return new SyncPromise<{ ready: boolean; interval: number }>(resolve => {
      let ticked: number = 0;
      const tick: number = 1;

      let interval = 0;
      clearInterval(interval);

      interval = (setInterval(() => {
        if (!this._processing) {
          resolve({
            interval,
            ready: true,
          });
        } else {
          ticked += tick;
          if (timeout && ticked >= timeout) {
            resolve({
github getsentry / sentry-javascript / packages / node / src / parsers.ts View on Github external
export function getExceptionFromError(error: Error, options?: NodeOptions): PromiseLike {
  const name = error.name || error.constructor.name;
  const stack = extractStackFromError(error);
  return new SyncPromise(resolve =>
    parseStack(stack, options).then(frames => {
      const result = {
        stacktrace: {
          frames: prepareFramesForEvent(frames),
        },
        type: name,
        value: error.message,
      };
      resolve(result);
    }),
  );
}