LogoLogo
  • Overview
  • Key Features
  • Getting Started
    • Installation
    • Quick Start Guide
    • Configuration Options
    • Authentication
  • NPM Package
    • Installation
    • Core API Reference
    • Event Tracking
    • Experimentation
    • Performance Monitoring
    • Session Recording
    • Error Tracking
    • Advanced Configuration
  • A/B Testing & Experimentation
    • Creating Experiments
    • Targeting Users
    • Measuring Results
    • Statistics & Significance
    • Best Practices
  • Analytics Dashboard
    • Overview
    • User Journey Analysis
    • Conversion Funnels
    • Custom Reports
  • Session Recording
    • Privacy Considerations
    • Viewing Recordings
    • Filtering & Searching
    • Heatmaps
  • Performance Monitoring
    • Core Web Vitals
  • User Management
    • Roles & Permissions
    • Team Collaboration
    • Access Controls
    • Audit Logs
  • Troubleshooting
    • Common Issues
    • Debugging Tools
    • Error Reference
  • Appendix
    • Glossary
    • API Status Codes
    • Migration Guides
    • Release Notes
    • Roadmap
Powered by GitBook
On this page
  • Enabling Error Tracking
  • Types of Errors Captured
  • Error Data Structure
  • Manual Error Tracking
  • Error Context & Breadcrumbs
  • Integration with Session Recording
  • Error Grouping and Analysis
  • Error Alerting
  • Source Maps Integration
  • Client Implementation
  • JavaScript Integration
  1. NPM Package

Error Tracking

Mtrix's error tracking provides comprehensive monitoring of client-side errors, helping you identify, prioritize, and fix issues before they impact your users. This section covers how to implement and leverage error tracking in your application.

Enabling Error Tracking

Error tracking is disabled by default. Enable it during initialization:

mtrix.init({
  organizationId: 'your-organization-id',
  projectId: 'your-project-id',
  environment: 'production',
  options: {
    errorReporting: {
      tracking: true,
      captureTypes: ['exception', 'promise', 'network', 'console'],
      ignoreErrors: ['Script error.', /Chrome Extensions/],
      maxErrorsPerMinute: 10,
      recordStackTrace: true,
      recordContext: true
    }
  }
});

Types of Errors Captured

Mtrix can capture different types of errors based on your configuration:

Unhandled Exceptions

JavaScript exceptions that aren't caught in try-catch blocks:

// This will be automatically captured
function buggyFunction() {
  const obj = null;
  return obj.property; // TypeError: Cannot read property 'property' of null
}

Promise Rejections

Unhandled promise rejections:

// This will be captured
fetch('/api/data')
  .then(response => {
    if (!response.ok) {
      throw new Error('API request failed');
    }
    return response.json();
  })
  // Missing .catch() handler will be captured

Network Errors

Failed API requests and other network failures:

// Failed requests are captured
fetch('https://api.example.com/data')
  .then(response => {
    // 4xx and 5xx responses are captured
    return response.json();
  })
  .catch(error => {
    // Network errors are captured
    console.error('Fetch error:', error);
  });

Console Errors

Errors logged to the console:

// This will be captured if console capturing is enabled
console.error('Payment processing failed:', errorDetails);

Error Data Structure

Mtrix collects comprehensive data for each error:

{
  "errorId": "err-1a2b3c4d5e6f7g8h9i",
  "errorType": "exception",
  "message": "Cannot read property 'data' of undefined",
  "stack": "TypeError: Cannot read property 'data' of undefined\n    at processResponse (app.js:143)\n    at handleApiResponse (app.js:89)\n    at app.js:54",
  "timestamp": 1647532967843,
  "url": "https://example.com/dashboard",
  "source": "app.js",
  "lineno": 143,
  "colno": 32,
  "userId": "user-123abc",
  "sessionId": "sess-1a2b3c4d5e6f7g8h9i",
  "browser": "Chrome",
  "browserVersion": "98.0.4758.102",
  "os": "macOS",
  "osVersion": "12.2.1",
  "deviceType": "Desktop",
  "context": {
    "componentState": {
      "isLoading": false,
      "hasError": true
    },
    "apiRequest": {
      "url": "/api/user/dashboard",
      "method": "GET"
    },
    "breadcrumbs": [
      { "action": "pageView", "route": "/dashboard", "timestamp": 1647532960000 },
      { "action": "apiRequest", "url": "/api/user/dashboard", "timestamp": 1647532965000 },
      { "action": "error", "timestamp": 1647532967843 }
    ]
  }
}

Manual Error Tracking

In addition to automatic capture, you can manually track errors:

try {
  // Risky operation
  processUserData(userData);
} catch (error) {
  // Track the error with Mtrix
  mtrix.trackError({
    errorType: 'custom',
    message: error.message,
    stack: error.stack,
    context: {
      userData: sanitizeUserData(userData), // Remove sensitive data
      component: 'UserProfileProcessor'
    }
  });
  
  // Show user-friendly message
  showErrorNotification('Unable to process your profile. Please try again.');
}

Error Context & Breadcrumbs

Add custom context to help with debugging:

// Set global context that will be included with all errors
mtrix.setErrorContext({
  currentRoute: '/checkout/payment',
  userType: 'premium',
  cartValue: 125.50
});

// Add breadcrumbs to track user journey before errors
function addBreadcrumb(action, data) {
  mtrix.addErrorBreadcrumb(action, {
    ...data,
    timestamp: Date.now()
  });
}

// Example usage
addBreadcrumb('viewedProduct', { productId: '12345' });
addBreadcrumb('addedToCart', { productId: '12345', quantity: 2 });
addBreadcrumb('startedCheckout', { cartValue: 125.50 });

Integration with Session Recording

Mtrix can automatically trigger session recording when errors occur:

mtrix.init({
  // ... other config
  options: {
    errorReporting: {
      tracking: true
    },
    sessionRecording: {
      tracking: true,
      sampleRatio: 0.1, // 10% of normal sessions
      priority: 'error' // Always record sessions with errors
    }
  }
});

This creates a powerful debugging workflow:

  1. Error occurs and is captured by Mtrix

  2. Session recording is automatically triggered

  3. You can watch exactly what the user did before encountering the error

Error Grouping and Analysis

In the Mtrix dashboard, errors are automatically grouped based on:

  • Error message and type

  • File and line number

  • Stack trace similarity

This helps you focus on the most impactful issues:

TypeError: Cannot read property 'data' of undefined
    at processResponse (app.js:143)

    • 842 occurrences
    • First seen: April 10, 2025
    • Last seen: April 12, 2025
    • Affecting: 376 users
    • Browsers: Chrome (75%), Safari (20%), Firefox (5%)
    • Related events: "ApiRequestFailed" (65% correlation)

Error Alerting

Configure alerts based on error frequency, impact, or specific conditions:

Alerts can be delivered via:

  • Email

  • Slack

  • PagerDuty

  • Webhook (for custom integrations)

Source Maps Integration

For accurate line numbers in minified code, upload source maps to Mtrix:

// In your build process, upload source maps
const fs = require('fs');
const fetch = require('node-fetch');

async function uploadSourceMap(file, map) {
  const formData = new FormData();
  formData.append('file', fs.createReadStream(file));
  formData.append('sourceMap', fs.createReadStream(map));
  formData.append('version', process.env.BUILD_VERSION);
  
  await fetch('https://api.mtrix.io/v1/sourcemaps', {
    method: 'POST',
    headers: {
      'X-Mtrix-Organization': 'your-organization-id',
      'X-Mtrix-Project': 'your-project-id'
    },
    body: formData
  });
}

uploadSourceMap('./dist/app.min.js', './dist/app.min.js.map')
  .then(() => console.log('Source map uploaded'));

Client Implementation

This section provides detailed guidance on integrating Mtrix with various frontend frameworks and platforms.

JavaScript Integration

Basic HTML/JavaScript

For traditional websites without a frontend framework:

<!DOCTYPE html>
<html>
<head>
  <title>My Website</title>
  <!-- Include Mtrix from CDN in the head -->
  <script src="https://cdn.mtrix.io/v1/mtrix.min.js"></script>
  <script>
    // Initialize as early as possible
    mtrix.init({
      organizationId: 'your-organization-id',
      projectId: 'your-project-id',
      environment: 'production'
    });
  </script>
</head>
<body>
  <h1>Welcome to My Website</h1>
  <button id="signup-button">Sign Up</button>
  
  <script>
    // Track custom events
    document.getElementById('signup-button').addEventListener('click', function() {
      mtrix.trackEvent('SignupButtonClicked', {
        location: 'homepage',
        buttonText: this.textContent
      });
      
      // Redirect to signup page
      window.location.href = '/signup';
    });
  </script>
</body>
</html>

Using Module Bundlers

For projects using Webpack, Rollup, or other bundlers:

// Import at the entry point of your application
import mtrix from 'mtrix';

// Initialize early in the application lifecycle
mtrix.init({
  organizationId: 'your-organization-id',
  projectId: 'your-project-id',
  environment: process.env.NODE_ENV
});

// Later in your code, track events
function handlePurchase(product, quantity) {
  // Process purchase...
  
  // Then track the event
  mtrix.trackEvent('Purchase', {
    productId: product.id,
    productName: product.name,
    quantity,
    price: product.price,
    total: product.price * quantity
  });
}

PreviousSession RecordingNextAdvanced Configuration

Last updated 1 month ago