Skip to main content

Overview

The useErrorTracking hook provides methods for tracking JavaScript errors and custom error events. It also automatically tracks unhandled errors and promise rejections when the component is mounted.

Usage

import { useErrorTracking } from 'mentiq-sdk';

function MyComponent() {
  const { trackJavaScriptError, trackCustomError } = useErrorTracking();

  const handleAction = async () => {
    try {
      await riskyOperation();
    } catch (error) {
      trackJavaScriptError(error as Error, {
        action: 'riskyOperation',
        component: 'MyComponent'
      });
    }
  };

  return <button onClick={handleAction}>Execute</button>;
}

Automatic Error Tracking

When mounted, useErrorTracking automatically listens for:
  • JavaScript errors (window.error event)
  • Unhandled promise rejections (window.unhandledrejection event)
These errors are automatically tracked with contextual information including filename, line number, and column number.

Returns

trackJavaScriptError
function
Track JavaScript Error objects with additional contextSignature: (error: Error, properties?: EventProperties) => void
try {
  throw new Error('Something went wrong');
} catch (error) {
  trackJavaScriptError(error as Error, {
    component: 'UserProfile',
    action: 'loadUserData',
    userId: 'user-123'
  });
}
Tracked Data:
  • message: Error message
  • stack: Stack trace
  • Any additional properties passed
trackCustomError
function
Track custom error messages with optional contextSignature: (message: string, properties?: EventProperties) => void
if (response.status === 404) {
  trackCustomError('Resource not found', {
    endpoint: '/api/users/123',
    statusCode: 404,
    method: 'GET'
  });
}
Tracked Data:
  • message: Custom error message
  • Any additional properties passed

Type Definitions

EventProperties

interface EventProperties {
  [key: string]: string | number | boolean | null | undefined;
}

Examples

API Error Tracking

import { useErrorTracking } from 'mentiq-sdk';

function DataFetcher() {
  const { trackCustomError } = useErrorTracking();

  const fetchData = async () => {
    try {
      const response = await fetch('/api/data');
      
      if (!response.ok) {
        trackCustomError('API request failed', {
          endpoint: '/api/data',
          status: response.status,
          statusText: response.statusText
        });
      }
      
      return response.json();
    } catch (error) {
      trackCustomError('Network error', {
        endpoint: '/api/data',
        error: error.message
      });
    }
  };

  return <button onClick={fetchData}>Load Data</button>;
}

Form Validation Errors

import { useErrorTracking } from 'mentiq-sdk';
import { useState } from 'react';

function SignupForm() {
  const { trackCustomError } = useErrorTracking();
  const [email, setEmail] = useState('');

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    if (!email.includes('@')) {
      trackCustomError('Invalid email format', {
        form: 'signup',
        field: 'email',
        value: email.substring(0, 10) // Don't send full email for privacy
      });
      return;
    }

    // Submit form...
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />
      <button type="submit">Sign Up</button>
    </form>
  );
}

React Error Boundary Integration

import { Component, ReactNode } from 'react';
import { Analytics } from 'mentiq-sdk';

interface Props {
  children: ReactNode;
  analytics: Analytics;
}

interface State {
  hasError: boolean;
}

class ErrorBoundary extends Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError() {
    return { hasError: true };
  }

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    // Track the error using the analytics instance
    this.props.analytics.trackCustomError(error, {
      componentStack: errorInfo.componentStack,
      errorBoundary: true
    });
  }

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children;
  }
}

Tracking Third-Party Library Errors

import { useErrorTracking } from 'mentiq-sdk';
import { useEffect } from 'react';

function ChartComponent() {
  const { trackJavaScriptError } = useErrorTracking();

  useEffect(() => {
    try {
      // Initialize chart library
      const chart = new SomeChartLibrary({
        onError: (error) => {
          trackJavaScriptError(error, {
            library: 'SomeChartLibrary',
            component: 'ChartComponent'
          });
        }
      });

      return () => chart.destroy();
    } catch (error) {
      trackJavaScriptError(error as Error, {
        phase: 'initialization',
        library: 'SomeChartLibrary'
      });
    }
  }, [trackJavaScriptError]);

  return <div id="chart-container" />;
}

Automatic Tracking Details

JavaScript Errors

Automatically tracked with:
  • message: Error message
  • stack: Stack trace
  • filename: File where error occurred
  • lineno: Line number
  • colno: Column number

Unhandled Promise Rejections

Automatically tracked with:
  • message: Rejection reason
  • type: “unhandledrejection”

Notes

Error tracking is automatically enabled when the component mounts and disabled when it unmounts. Only mount this hook in components that persist throughout your app lifecycle, or use it selectively where needed.
Combine error tracking with session data to understand the context in which errors occur and identify patterns in user behavior that lead to errors.
Avoid tracking sensitive information in error properties. Always sanitize user data before including it in error tracking.

Build docs developers (and LLMs) love