CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-rollbar

JavaScript error tracking and monitoring library for Node.js and browser environments with telemetry, automatic error grouping, and real-time notifications

Pending
Overview
Eval results
Files

browser-integration.mddocs/

Browser Integration

Browser-specific error handling features including global error capture, DOM event telemetry, function wrapping, and automatic instrumentation for enhanced client-side error tracking.

Capabilities

Function Wrapping

Wrap functions with error handling and context preservation.

/**
 * Wrap a function with error handling and optional context
 * @param fn - Function to wrap with error handling
 * @param context - Optional context object for additional data
 * @param before - Optional function to call before wrapped function
 * @returns Wrapped function that reports errors to Rollbar
 */
function wrap(fn: Function, context?: any, before?: Function): Function;

Usage Examples:

// Basic function wrapping
const safeFn = rollbar.wrap(function() {
  throw new Error('This will be caught and reported');
});

// With context
const processData = rollbar.wrap(function(data) {
  // Process data
  return data.map(item => item.value);
}, { operation: 'data-processing' });

// With before hook
const apiCall = rollbar.wrap(
  function(endpoint) {
    return fetch(endpoint);
  },
  { module: 'api' },
  function(args) {
    console.log('Making API call to:', args[0]);
  }
);

Global Error Handling

Automatically capture uncaught exceptions and unhandled promise rejections.

// Configuration options for global error handling
captureUncaught?: boolean;
captureUnhandledRejections?: boolean;

Configuration Example:

const rollbar = new Rollbar({
  accessToken: 'YOUR_CLIENT_ACCESS_TOKEN',
  captureUncaught: true, // Capture window.onerror events
  captureUnhandledRejections: true, // Capture unhandled promise rejections
  environment: 'production'
});

DOM Event Telemetry

Capture DOM events and user interactions for debugging context.

/**
 * Capture custom telemetry events
 * @param metadata - Event metadata
 * @param level - Event severity level
 * @returns Telemetry event object
 */
function captureEvent(metadata: object, level: Level): TelemetryEvent;

interface TelemetryEvent {
  level: Level;
  type: string;
  timestamp_ms: number;
  body: object;
  source: string;
  uuid?: string;
}

Usage Examples:

// Capture custom user interaction
document.getElementById('submit-btn').addEventListener('click', function(e) {
  rollbar.captureEvent({
    type: 'click',
    element: 'submit-button',
    userId: getCurrentUser().id
  }, 'info');
});

// Capture form submission
document.getElementById('contact-form').addEventListener('submit', function(e) {
  rollbar.captureEvent({
    type: 'form_submit',
    form: 'contact',
    fields: Object.keys(new FormData(e.target)).length
  }, 'info');
});

Anonymous Error Detection

Detect and handle Chrome's anonymous errors.

inspectAnonymousErrors?: boolean;

Chrome sometimes reports errors as "Script error" without details. This option enables inspection of anonymous errors.

Configuration Example:

const rollbar = new Rollbar({
  accessToken: 'YOUR_ACCESS_TOKEN',
  inspectAnonymousErrors: true // Enable anonymous error inspection
});

Global Event Handler Wrapping

Automatically wrap global event handlers with error reporting.

wrapGlobalEventHandlers?: boolean;

Configuration Example:

const rollbar = new Rollbar({
  accessToken: 'YOUR_ACCESS_TOKEN',
  wrapGlobalEventHandlers: true // Wrap setTimeout, setInterval, etc.
});

Auto-Instrumentation

Comprehensive automatic instrumentation for browser events and interactions.

interface AutoInstrumentSettings {
  network?: boolean;
  networkResponseHeaders?: boolean | string[];
  networkResponseBody?: boolean;
  networkRequestBody?: boolean;
  log?: boolean;
  dom?: boolean;
  navigation?: boolean;
  connectivity?: boolean;
  contentSecurityPolicy?: boolean;
  errorOnContentSecurityPolicy?: boolean;
}

type AutoInstrumentOptions = boolean | AutoInstrumentSettings;

Network Instrumentation

Automatically capture network requests and responses.

Configuration Example:

const rollbar = new Rollbar({
  accessToken: 'YOUR_ACCESS_TOKEN',
  autoInstrument: {
    network: true,
    networkResponseHeaders: ['content-type', 'x-request-id'],
    networkResponseBody: true,
    networkRequestBody: false // Don't capture request bodies
  }
});

DOM Instrumentation

Capture DOM events and user interactions.

Configuration Example:

const rollbar = new Rollbar({
  accessToken: 'YOUR_ACCESS_TOKEN',
  autoInstrument: {
    dom: true, // Capture clicks, form submissions, etc.
    navigation: true, // Capture page navigation events
    connectivity: true // Capture online/offline events
  }
});

Console Log Instrumentation

Automatically capture console.log, console.error, etc.

Configuration Example:

const rollbar = new Rollbar({
  accessToken: 'YOUR_ACCESS_TOKEN',
  autoInstrument: {
    log: true // Capture console logs as telemetry
  }
});

Telemetry Scrubbing

Control what DOM elements and data are captured in telemetry.

type TelemetryScrubber = (description: TelemetryScrubberInput) => boolean;

type TelemetryScrubberInput = DomDescription | null;

interface DomDescription {
  tagName: string;
  id: string | undefined;
  classes: string[] | undefined;
  attributes: DomAttribute[];
}

interface DomAttribute {
  key: DomAttributeKey;
  value: string;
}

type DomAttributeKey = 'type' | 'name' | 'title' | 'alt';

Usage Example:

const rollbar = new Rollbar({
  accessToken: 'YOUR_ACCESS_TOKEN',
  telemetryScrubber: (description) => {
    if (!description) return false;
    
    // Don't capture password fields
    if (description.attributes.some(attr => 
      attr.key === 'type' && attr.value === 'password'
    )) {
      return true; // Scrub this element
    }
    
    // Don't capture elements with sensitive classes
    if (description.classes && 
        description.classes.some(cls => cls.includes('sensitive'))) {
      return true;
    }
    
    return false; // Don't scrub
  }
});

Browser-Specific Configuration

Stack Trace Limit

Control the maximum number of stack frames captured.

stackTraceLimit?: number;

Source Map Configuration

Enable source map processing for better error reporting.

interface BrowserPayload {
  client?: {
    javascript?: {
      source_map_enabled?: boolean;
      guess_uncaught_frames?: boolean;
      code_version?: string;
    };
  };
}

Configuration Example:

const rollbar = new Rollbar({
  accessToken: 'YOUR_ACCESS_TOKEN',
  payload: {
    client: {
      javascript: {
        source_map_enabled: true,
        guess_uncaught_frames: true,
        code_version: '1.2.3'
      }
    }
  }
});

Complete Browser Setup Example

<!DOCTYPE html>
<html>
<head>
  <title>Rollbar Browser Example</title>
  <script src="https://cdn.rollbar.com/rollbar.umd.min.js"></script>
</head>
<body>
  <h1>My App</h1>
  <button id="error-btn">Trigger Error</button>
  <button id="custom-event">Custom Event</button>
  
  <script>
    // Initialize Rollbar
    const rollbar = new Rollbar({
      accessToken: 'YOUR_POST_CLIENT_ITEM_ACCESS_TOKEN',
      environment: 'production',
      
      // Global error handling
      captureUncaught: true,
      captureUnhandledRejections: true,
      
      // Browser-specific options
      inspectAnonymousErrors: true,
      wrapGlobalEventHandlers: true,
      stackTraceLimit: 50,
      
      // Auto-instrumentation
      autoInstrument: {
        network: true,
        networkResponseHeaders: ['content-type'],
        dom: true,
        navigation: true,
        connectivity: true,
        log: true
      },
      
      // Telemetry settings
      maxTelemetryEvents: 100,
      includeItemsInTelemetry: true,
      
      // Source maps
      payload: {
        client: {
          javascript: {
            source_map_enabled: true,
            code_version: '1.0.0'
          }
        },
        person: {
          id: getUserId(),
          username: getUsername(),
          email: getUserEmail()
        }
      },
      
      // Custom telemetry scrubber
      telemetryScrubber: (description) => {
        if (!description) return false;
        
        // Scrub password fields
        return description.attributes.some(attr => 
          attr.key === 'type' && attr.value === 'password'
        );
      }
    });
    
    // Set up event handlers
    document.getElementById('error-btn').addEventListener('click', 
      rollbar.wrap(function() {
        throw new Error('Intentional error for testing');
      }, { button: 'error-btn' })
    );
    
    document.getElementById('custom-event').addEventListener('click', function() {
      rollbar.captureEvent({
        type: 'button_click',
        button: 'custom-event',
        timestamp: Date.now()
      }, 'info');
      
      rollbar.info('Custom event button clicked');
    });
    
    // Example of manual error reporting
    window.addEventListener('load', function() {
      rollbar.info('Page loaded successfully');
    });
    
    // Helper functions (implement according to your auth system)
    function getUserId() {
      return localStorage.getItem('userId') || 'anonymous';
    }
    
    function getUsername() {
      return localStorage.getItem('username') || 'guest';
    }
    
    function getUserEmail() {
      return localStorage.getItem('userEmail') || '';
    }
  </script>
</body>
</html>

Single Page Application (SPA) Integration

// For React, Vue, Angular, etc.
const rollbar = new Rollbar({
  accessToken: 'YOUR_ACCESS_TOKEN',
  environment: 'production',
  captureUncaught: true,
  captureUnhandledRejections: true,
  
  // SPA-specific settings
  autoInstrument: {
    network: true,
    navigation: true, // Important for SPA route changes
    dom: true
  },
  
  // Custom transform for SPA context
  transform: function(data, item) {
    // Add current route information
    data.context = {
      route: window.location.pathname,
      component: getCurrentComponent(), // Your SPA-specific function
      userId: getCurrentUserId()
    };
  }
});

// Example: Capture route changes
function onRouteChange(newRoute) {
  rollbar.captureEvent({
    type: 'navigation',
    from: oldRoute,
    to: newRoute,
    timestamp: Date.now()
  }, 'info');
}

Install with Tessl CLI

npx tessl i tessl/npm-rollbar

docs

browser-integration.md

configuration.md

core-logging.md

index.md

react-native-integration.md

server-integration.md

telemetry.md

tile.json