# Error Filtering in BugMail SDK

## Overview

The BugMail SDK includes intelligent error filtering to prevent it from reporting its own internal errors. This prevents infinite loops, reduces noise in your error dashboard, and ensures you only see errors from your application code.

## What Errors Are Filtered?

The SDK automatically filters out errors that originate from its own code. Specifically, it filters:

### 1. SDK Internal Errors

Any error whose stack trace contains SDK-specific patterns:
- `@bugmail-js`
- `bugmail-sdk`
- `bugmail-client`
- `bugmail-core`
- `network-manager`
- `error-processor`
- `context-collector`
- `error-filter`

### 2. SDK Console Messages

Console errors that start with SDK-specific prefixes:
- `[BugMail`
- `BugMail Network`
- `BugMail SDK`
- `BugMail:`

### 3. Network Errors

Errors that occur when the SDK communicates with the BugMail backend:
- API validation failures (invalid API key, inactive key, etc.)
- Network connectivity issues
- Server errors during error submission

### 4. SDK State Errors

Errors that occur when the SDK is already handling an internal error (prevents cascading failures).

## Why Filter These Errors?

### Preventing Infinite Loops

Without filtering, the SDK could create infinite loops:

```
1. SDK tries to send error with invalid API key
2. Backend returns 401 error
3. SDK logs error to console.error
4. Console capture detects the error
5. SDK tries to send this new error
6. Backend returns 401 error again
7. Loop continues forever...
```

With filtering, step 4 detects that the error originated from SDK code and stops the loop.

### Reducing Noise

SDK internal errors are not actionable for developers using the SDK. They represent:
- Configuration issues (wrong API key)
- Temporary network problems
- Backend service issues

These should be logged locally for debugging but not sent to your error dashboard.

### Improving Performance

Filtering prevents unnecessary network requests and reduces bandwidth usage when the SDK encounters issues.

## How Filtering Works

The SDK uses a multi-layered approach to filter errors:

### Layer 1: Error Origin Detection

```javascript
// Check if error originated from SDK code
if (error.stack && error.stack.includes('@bugmail-js')) {
  // Filter out - this is an SDK error
  return;
}
```

### Layer 2: Message Pattern Matching

```javascript
// Check if error message contains SDK patterns
if (error.message && error.message.includes('[BugMail')) {
  // Filter out - this is an SDK message
  return;
}
```

### Layer 3: Call Stack Analysis

```javascript
// Check if current call originated from SDK code
const stack = new Error().stack;
if (stack.includes('bugmail-client')) {
  // Filter out - called from SDK code
  return;
}
```

### Layer 4: Internal State Check

```javascript
// Check if SDK is in internal error state
if (this._isInternalError) {
  // Filter out - SDK is handling its own error
  return;
}
```

## Debug Mode

Enable debug mode to see what errors are being filtered and why:

```javascript
const bugmail = new BugMail({
  apiKey: 'YOUR_API_KEY',
  debug: true  // Enable debug logging
});
```

With debug mode enabled, you'll see console messages like:

```
[BugMail Filter] Filtered: SDK pattern in message: [BugMail Network] Failed to send error
[BugMail Filter] Filtered: SDK pattern in stack trace
[BugMail Filter] Filtered: Error originated from SDK code
```

## Common Scenarios

### Scenario 1: Invalid API Key

**What happens:**
1. SDK tries to send error with invalid API key
2. Backend returns 401 Unauthorized
3. SDK logs: `[BugMail Network] Failed to send error: 401`
4. Error filter detects `[BugMail Network]` prefix
5. Error is NOT captured or sent again
6. You see one console message, no loop

**What you see in console:**
```
[BugMail Network] Failed to send error: { status: 401, body: { detail: "Invalid API key" } }
```

**What you DON'T see:**
- Repeated error messages
- Network requests in a loop
- Errors in your BugMail dashboard

### Scenario 2: Network Connectivity Issue

**What happens:**
1. SDK tries to send error but network is down
2. Fetch fails with network error
3. SDK logs: `[BugMail Network] Failed to send error: network_error`
4. Error filter detects `[BugMail Network]` prefix
5. Error is NOT captured
6. SDK stores error offline (if configured)

**What you see in console:**
```
[BugMail Network] Failed to send error: { status: 'network_error', message: 'Failed to fetch' }
```

### Scenario 3: SDK Code Throws Error

**What happens:**
1. Bug in SDK code causes error
2. Error has SDK files in stack trace
3. Error filter detects SDK patterns in stack
4. Error is NOT captured
5. Error is logged locally for debugging

**What you see in console:**
```
Error in bugmail-client.js: ...
[BugMail Filter] Filtered: SDK pattern in stack trace
```

### Scenario 4: Your Application Error

**What happens:**
1. Your code throws an error
2. SDK captures the error
3. Error filter checks stack trace
4. No SDK patterns found
5. Error IS captured and sent to backend
6. Error appears in your dashboard

**What you see in console:**
```
TypeError: Cannot read property 'foo' of undefined
    at MyComponent.render (app.js:123)
```

**What you see in dashboard:**
- Full error details
- Stack trace
- User context
- Breadcrumbs

## Troubleshooting

### "My SDK errors aren't appearing in the dashboard"

This is expected behavior! SDK errors are intentionally filtered out. If you need to debug SDK issues:

1. Enable debug mode:
```javascript
const bugmail = new BugMail({
  apiKey: 'YOUR_API_KEY',
  debug: true
});
```

2. Check browser console for `[BugMail]` prefixed messages

3. Check network tab for failed requests

### "I want to see SDK errors in my dashboard"

SDK errors are filtered for good reasons (preventing loops, reducing noise). However, if you really need to see them:

1. Check browser console - all SDK errors are logged there
2. Use browser DevTools Network tab to see failed requests
3. Enable debug mode for detailed logging

If you believe an SDK error should be reported, please file an issue on GitHub.

### "How do I know if my API key is valid?"

If your API key is invalid, you'll see console messages:

```
[BugMail Network] Failed to send error: { status: 401, body: { detail: "Invalid API key" } }
```

To verify your API key:
1. Check that it matches your project API key in BugMail dashboard
2. Ensure there are no extra spaces or characters
3. Verify the key is active (not revoked)

### "Errors are being filtered that shouldn't be"

If legitimate application errors are being filtered:

1. Check if your code includes "bugmail" in filenames or paths
2. Avoid using `[BugMail` prefix in your error messages
3. Enable debug mode to see why errors are filtered
4. File an issue on GitHub with details

## Advanced: Custom Filtering

If you need to filter additional errors beyond SDK errors, you can use the `beforeSend` hook:

```javascript
const bugmail = new BugMail({
  apiKey: 'YOUR_API_KEY',
  beforeSend: (error, context) => {
    // Filter out errors from third-party scripts
    if (error.stack && error.stack.includes('third-party-lib')) {
      return null;  // Don't send this error
    }
    
    // Filter out specific error messages
    if (error.message.includes('ResizeObserver loop')) {
      return null;  // Don't send this error
    }
    
    // Modify error before sending
    error.customField = 'custom value';
    
    return error;  // Send modified error
  }
});
```

## Technical Details

### ErrorFilter Class

The SDK uses an `ErrorFilter` class to centralize filtering logic:

```javascript
class ErrorFilter {
  shouldCaptureError(error, context) {
    // Returns true if error should be captured
    // Returns false if error should be filtered
  }
  
  shouldCaptureConsoleError(args) {
    // Returns true if console message should be captured
    // Returns false if console message should be filtered
  }
}
```

### Integration Points

Error filtering is applied at multiple points:

1. **Window Error Handler** - Filters `window.onerror` events
2. **Unhandled Rejection Handler** - Filters `unhandledrejection` events
3. **Console Capture** - Filters `console.error` calls
4. **Manual Capture** - Filters `bugmail.captureError()` calls
5. **Network Manager** - Prevents network errors from being captured

### Performance Impact

Error filtering is designed to be lightweight:
- Simple string matching operations
- No regex (faster)
- Early returns to avoid unnecessary checks
- Minimal memory overhead

Typical filtering check takes < 1ms.

## FAQ

### Q: Will filtering affect my application's error reporting?

**A:** No. Filtering only affects SDK internal errors. Your application errors are captured normally.

### Q: Can I disable error filtering?

**A:** No. Error filtering is essential to prevent infinite loops and is always enabled. However, you can use debug mode to see what's being filtered.

### Q: What if I need to debug SDK issues?

**A:** Enable debug mode and check browser console. All SDK errors are logged there with detailed information.

### Q: Does filtering work with source maps?

**A:** Yes. The filter checks both minified and unminified code patterns.

### Q: What about errors in my code that mention "bugmail"?

**A:** If your application code has "bugmail" in filenames or error messages, those errors might be filtered. Avoid using SDK-specific patterns in your code.

### Q: How do I report SDK bugs?

**A:** SDK errors are logged to console. Copy the error message and stack trace, then file an issue on GitHub: https://github.com/yourusername/bugmail-sdk/issues

### Q: Does filtering work in all browsers?

**A:** Yes. Error filtering uses standard JavaScript features supported in all modern browsers (Chrome 60+, Firefox 55+, Safari 11+, Edge 16+).

### Q: What about errors in production builds?

**A:** Filtering works the same in development and production. Minified code is still filtered correctly.

## Related Documentation

- [SDK Configuration](./CONFIGURATION.md)
- [Error Handling Best Practices](./ERROR_HANDLING.md)
- [Troubleshooting Guide](./TROUBLESHOOTING.md)
- [API Reference](./API_REFERENCE.md)

## Support

If you have questions about error filtering:

1. Check this documentation
2. Enable debug mode for detailed logging
3. Search existing GitHub issues
4. File a new issue with details

For urgent issues, contact support@bugmail.io
