Skip to content
Merged
Show file tree
Hide file tree
Changes from 62 commits
Commits
Show all changes
69 commits
Select commit Hold shift + click to select a range
592f6e2
feat: add public interface
ioannisj Oct 15, 2025
23f7ba9
feat: add config and exception processor
ioannisj Oct 15, 2025
7f3dc16
feat: native plugins
ioannisj Oct 15, 2025
8b40927
chore: update sample app
ioannisj Oct 15, 2025
7c55c87
feat: add unit tests
ioannisj Oct 15, 2025
b0bafda
feat: handle primitives
ioannisj Oct 15, 2025
73f6e1b
chore: update changelog
ioannisj Oct 16, 2025
742f23f
fix: package and module
ioannisj Oct 16, 2025
dd88514
feat: add autocapture integration
ioannisj Oct 17, 2025
248ea91
chore: update changelog
ioannisj Oct 17, 2025
cf504fb
fix: format
ioannisj Oct 17, 2025
e137c1e
fix: format
ioannisj Oct 17, 2025
6fb190d
fix: use Object vs dynamic
ioannisj Oct 17, 2025
7744b92
chore: rename folder
ioannisj Oct 17, 2025
e32fee1
fix: make stackTrace optional
ioannisj Oct 17, 2025
c35cb81
fix: clean generated stack trace
ioannisj Oct 18, 2025
cfe8868
feat: add unit tests
ioannisj Oct 18, 2025
16577ed
fix: make function optional
ioannisj Oct 18, 2025
f5ff9c5
fix: drop primitive check
ioannisj Oct 19, 2025
2ef7146
fix: skip module
ioannisj Oct 19, 2025
690bae0
fix: make thread_id optional
ioannisj Oct 19, 2025
1651e5c
fix: update config
ioannisj Oct 19, 2025
585a68e
fix: error type
ioannisj Oct 19, 2025
a5f22e4
fix: doc
ioannisj Oct 19, 2025
a077460
fix: handle empty stack trace
ioannisj Oct 20, 2025
c21b68c
fix: allow overwriting exception properties
ioannisj Oct 20, 2025
19d2c19
fix: normalize props
ioannisj Oct 21, 2025
e3d6680
chore: bump min dart and flutter version
ioannisj Oct 21, 2025
084a8b6
fix: generate event timestamp flutter side
ioannisj Oct 22, 2025
e5145d9
fix: remove handled from public api
ioannisj Oct 22, 2025
6514ab4
fix: platform call arguments
ioannisj Oct 23, 2025
821f05a
fix: example app
ioannisj Oct 23, 2025
907b8ec
fix: do not try to parse exception package
ioannisj Oct 23, 2025
5e19639
fix: normalize props
ioannisj Oct 23, 2025
298106d
fix: normalize sets
ioannisj Oct 23, 2025
bdec329
fix: remove handled from public interface
ioannisj Oct 23, 2025
d491713
fix: web handler
ioannisj Oct 23, 2025
59ed147
fix: replace hof with direct iteration
ioannisj Oct 23, 2025
5a6d7d7
fix:
ioannisj Oct 23, 2025
6c0529c
feat: add web support
ioannisj Oct 24, 2025
c4babf0
chore: add config comment
ioannisj Oct 24, 2025
be5ccfd
Merge branch 'feat/capture-exception' into feat/autocapture-exceptions
ioannisj Oct 24, 2025
fd00daf
feat: add async gap franes
ioannisj Oct 30, 2025
42443b4
Revert "feat: add web support"
ioannisj Oct 30, 2025
edeaa36
Merge branch 'feat/capture-exception' into feat/autocapture-exceptions
ioannisj Oct 30, 2025
f9e9fb9
fix: simplify config
ioannisj Oct 31, 2025
db5f8a6
feat: add config for native autocapture
ioannisj Nov 3, 2025
a8bf280
fix: avoid null-assertion
ioannisj Nov 3, 2025
3dca39d
fix: always restore original handlers
ioannisj Nov 3, 2025
cb2e261
fix: wrap error in PostHogException
ioannisj Nov 3, 2025
488fedc
feat: add test cases
ioannisj Nov 3, 2025
bf5d806
feat: capture additional details from FlutterErrorDetails
ioannisj Nov 3, 2025
4ec5010
fix: make install and uninstall methods private
ioannisj Nov 3, 2025
7e331da
fix: do not modify behavior
ioannisj Nov 3, 2025
a9da171
feat: add current isolate error handling
ioannisj Nov 4, 2025
2bea94e
fix: remove tests
ioannisj Nov 4, 2025
d0ee077
fix: annotate as internal
ioannisj Nov 4, 2025
c553ceb
fix: flutter analyze
ioannisj Nov 4, 2025
61599ff
fix: do not install PlatformDispatcher.instance.onError on web
ioannisj Nov 4, 2025
fb4bc95
chore: update changelog
ioannisj Nov 4, 2025
2c02178
Merge branch 'main' into feat/autocapture-exceptions
ioannisj Nov 4, 2025
7c7fd1a
fix: build
ioannisj Nov 4, 2025
042b1d0
chore: update changelog
ioannisj Nov 4, 2025
f06c1e2
fix: address feedback
ioannisj Nov 5, 2025
a9ec4ac
fix: mark IsolateErrorHandler as internal for now
ioannisj Nov 5, 2025
3d06c85
fix: type inference
ioannisj Nov 5, 2025
402a8ee
fix: update changelog
ioannisj Nov 5, 2025
277ffb9
fix: platform check
ioannisj Nov 5, 2025
adf48db
chore: update sample project
ioannisj Nov 5, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
## Next

- feat: add autocapture exceptions ([#214](https://github.com/PostHog/posthog-flutter/pull/214))
- **Note**: The following features are not yet supported:
- Flutter web platform (PlatformDispatcher.onError not implemented)
- Instrumentation to enable background isolate error auto capture
- Native iOS exception capture

## 5.8.0

- feat: surveys GA ([#215](https://github.com/PostHog/posthog-flutter/pull/215))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,16 @@ class PosthogFlutterPlugin :
}
}

// Configure error tracking autocapture
posthogConfig.getIfNotNull<Map<String, Any>>("errorTrackingConfig") { errorConfig ->
errorConfig.getIfNotNull<Boolean>("captureNativeExceptions") {
errorTrackingConfig.autoCapture = it
}
errorConfig.getIfNotNull<List<String>>("inAppIncludes") { includes ->
errorTrackingConfig.inAppIncludes.addAll(includes)
}
}

sdkName = "posthog-flutter"
sdkVersion = postHogVersion
}
Expand Down
7 changes: 7 additions & 0 deletions example/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@ Future<void> main() async {
config.sessionReplayConfig.maskAllImages = false;
config.sessionReplayConfig.throttleDelay = const Duration(milliseconds: 1000);
config.flushAt = 1;

// Configure error tracking and exception capture
config.errorTrackingConfig.captureFlutterErrors =
true; // Capture Flutter framework errors
config.errorTrackingConfig.capturePlatformDispatcherErrors =
true; // Capture Dart runtime errors

await Posthog().setup(config);

runApp(const MyApp());
Expand Down
24 changes: 18 additions & 6 deletions lib/src/error_tracking/dart_exception_processor.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import 'package:stack_trace/stack_trace.dart';
import 'utils/isolate_utils.dart' as isolate_utils;
import 'posthog_exception.dart';

class DartExceptionProcessor {
/// Converts Dart error/exception and stack trace to PostHog exception format
Expand All @@ -12,12 +13,23 @@ class DartExceptionProcessor {
bool inAppByDefault = true,
StackTrace Function()? stackTraceProvider, //for testing
}) {
// Extract PostHog metadata if error is wrapped in PostHogException
String mechanismType = 'generic';
bool handled = true;
Object currentError = error;

if (error is PostHogException) {
handled = error.handled;
mechanismType = error.mechanism;
currentError = error.source;
}

StackTrace? effectiveStackTrace = stackTrace;
bool isGeneratedStackTrace = false;

// If it's an Error, try to use its built-in stackTrace
if (error is Error) {
effectiveStackTrace ??= error.stackTrace;
if (currentError is Error) {
effectiveStackTrace ??= currentError.stackTrace;
}

// If still null or empty, get current stack trace
Expand All @@ -41,7 +53,7 @@ class DartExceptionProcessor {
)
: <Map<String, dynamic>>[];

final errorType = _getExceptionType(error);
final errorType = _getExceptionType(currentError);

// Mark exception as synthetic if:
// - runtimeType.toString() returned empty/null (fallback to 'Error' type)
Expand All @@ -53,14 +65,14 @@ class DartExceptionProcessor {
final exceptionData = <String, dynamic>{
'type': errorType ?? 'Error',
'mechanism': {
'handled': true, // always true for now
'handled': handled,
'synthetic': isSynthetic,
'type': 'generic',
'type': mechanismType,
}
};

// Add exception message, if available
final errorMessage = error.toString();
final errorMessage = currentError.toString();
if (errorMessage.isNotEmpty) {
exceptionData['value'] = errorMessage;
}
Expand Down
33 changes: 33 additions & 0 deletions lib/src/error_tracking/isolate_handler_io.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import 'dart:isolate';

import 'package:posthog_flutter/src/util/logging.dart';

/// Native platform implementation of isolate error handling
class IsolateErrorHandler {
RawReceivePort? _isolateErrorPort;

/// Add error listener to current isolate (should be main isolate)
void addErrorListener(Function(dynamic) onError) {
// In Flutter, the main isolate typically has debugName 'main'
final isolateName = Isolate.current.debugName;
if (isolateName != null && isolateName != 'main') {
printIfDebug(
'PostHog isolate error handler is being set up in isolate "$isolateName" instead of main isolate');
}

_isolateErrorPort = RawReceivePort(onError);
Isolate.current.addErrorListener(_isolateErrorPort!.sendPort);
}

/// Remove error listener and clean up
void removeErrorListener() {
if (_isolateErrorPort != null) {
_isolateErrorPort!.close();
Isolate.current.removeErrorListener(_isolateErrorPort!.sendPort);
_isolateErrorPort = null;
}
}

/// Check if error listener is active
bool get isActive => _isolateErrorPort != null;
}
16 changes: 16 additions & 0 deletions lib/src/error_tracking/isolate_handler_web.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/// Web platform stub implementation of isolate error handling
/// Isolates are not available on web, so this is a no-op implementation
class IsolateErrorHandler {
/// Add error listener to current isolate (no-op on web)
void addErrorListener(Function(dynamic) onError) {
// No-op: Isolates are not available on web
}

/// Remove error listener and clean up (no-op on web)
void removeErrorListener() {
// No-op: Isolates are not available on web
}

/// Check if error listener is active (always false on web)
bool get isActive => false;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,234 @@
import 'dart:ui';

import 'package:flutter/foundation.dart';
import 'package:posthog_flutter/src/util/platform_io_stub.dart';

import 'isolate_handler_io.dart'
if (dart.library.html) 'isolate_handler_web.dart';
import 'package:posthog_flutter/src/util/logging.dart';

import '../posthog_flutter_platform_interface.dart';
import '../posthog_config.dart';
import 'posthog_exception.dart';

/// Handles automatic capture of Flutter and Dart exceptions
class PostHogErrorTrackingAutoCaptureIntegration {
final PostHogErrorTrackingConfig _config;
final PosthogFlutterPlatformInterface _posthog;

// Store original handlers (we'll chain with them from our handler)
FlutterExceptionHandler? _originalFlutterErrorHandler;
ErrorCallback? _originalPlatformErrorHandler;

// Isolate error handling
final IsolateErrorHandler _isolateErrorHandler = IsolateErrorHandler();

bool _isEnabled = false;

static PostHogErrorTrackingAutoCaptureIntegration? _instance;

PostHogErrorTrackingAutoCaptureIntegration._({
required PostHogErrorTrackingConfig config,
required PosthogFlutterPlatformInterface posthog,
}) : _config = config,
_posthog = posthog;

/// Install the autocapture integration (can only be installed once)
static PostHogErrorTrackingAutoCaptureIntegration? install({
required PostHogErrorTrackingConfig config,
required PosthogFlutterPlatformInterface posthog,
}) {
if (_instance != null) {
debugPrint(
'PostHog: Error tracking autocapture integration is already installed. Call PostHogErrorTrackingAutoCaptureIntegration.uninstall() first.');
return null;
}

final instance = PostHogErrorTrackingAutoCaptureIntegration._(
config: config,
posthog: posthog,
);

_instance = instance;

if (config.captureFlutterErrors ||
config.capturePlatformDispatcherErrors ||
config.captureIsolateErrors) {
instance.start();
}

return instance;
}

/// Uninstall the autocapture integration
static void uninstall() {
if (_instance != null) {
_instance!.stop();
_instance = null;
}
}

/// Start automatic exception capture
void start() {
if (_isEnabled) return;

_isEnabled = true;

// Set up Flutter error handler if enabled
if (_config.captureFlutterErrors) {
_setupFlutterErrorHandler();
}

// Set up platform error handler if enabled
if (_config.capturePlatformDispatcherErrors) {
_setupPlatformErrorHandler();
}

// Set up isolate error handler if enabled
if (_config.captureIsolateErrors) {
_setupIsolateErrorHandler();
}
}

/// Stop automatic exception capture (restores original handlers)
void stop() {
if (!_isEnabled) return;

_isEnabled = false;

// Restore original handlers only if our own handler is still set
if (FlutterError.onError == _posthogFlutterErrorHandler) {
FlutterError.onError = _originalFlutterErrorHandler;
}
if (PlatformDispatcher.instance.onError == _posthogPlatformErrorHandler) {
PlatformDispatcher.instance.onError = _originalPlatformErrorHandler;
}

// Clean up isolate error handler
_isolateErrorHandler.removeErrorListener();

// release refs
_originalFlutterErrorHandler = null;
_originalPlatformErrorHandler = null;
}

/// Flutter framework error handler
void _setupFlutterErrorHandler() {
// prevent circular calls
if (FlutterError.onError == _posthogFlutterErrorHandler) {
return;
}

_originalFlutterErrorHandler = FlutterError.onError;

FlutterError.onError = _posthogFlutterErrorHandler;
}

void _posthogFlutterErrorHandler(FlutterErrorDetails details) {
if (!details.silent || _config.captureSilentFlutterErrors) {
// Collect additional context information
//(see: https://github.com/getsentry/sentry-dart/blob/a69a51fd1695dd93024be80a50ad05dd990b2b82/packages/flutter/lib/src/integrations/flutter_error_integration.dart#L35-L60)
final context = details.context?.toDescription();
final collector = details.informationCollector?.call() ?? [];
final information = collector.isNotEmpty
? (StringBuffer()..writeAll(collector, '\n')).toString()
: null;
final library = details.library;
final errorSummary = details.toStringShort();

// Build additional properties with Flutter-specific details
final flutterErrorDetails = <String, Object>{
if (context != null) 'context': 'thrown $context',
if (information != null) 'information': information,
if (library != null) 'library': library,
'error_summary': errorSummary,
'silent': details.silent,
};

final wrappedError = PostHogException(
source: details.exception, mechanism: 'FlutterError', handled: false);

_captureException(
error: wrappedError,
stackTrace: details.stack,
properties: {'flutter_error_details': flutterErrorDetails},
);
} else {
printIfDebug(
"Error not captured because FlutterErrorDetails.silent is true and captureSilentFlutterErrors is false");
}

// Call the original handler, if any
_originalFlutterErrorHandler?.call(details);
}

/// Platform error handler for Dart runtime errors
void _setupPlatformErrorHandler() {
// On web, PlatformDispatcher.onError is not implemented. Skip for now
// See: https://github.com/flutter/flutter/issues/100277
if (!isSupportedPlatform()) {
return;
}

// prevent circular calls
if (PlatformDispatcher.instance.onError == _posthogPlatformErrorHandler) {
return;
}

_originalPlatformErrorHandler = PlatformDispatcher.instance.onError;
PlatformDispatcher.instance.onError = _posthogPlatformErrorHandler;
}

bool _posthogPlatformErrorHandler(Object error, StackTrace stackTrace) {
final wrappedError = PostHogException(
source: error,
mechanism: 'PlatformDispatcher',
handled: false,
);

_captureException(error: wrappedError, stackTrace: stackTrace);

// Call the original handler, if any
// False otherwise, so that default fallback mechanism is used
return _originalPlatformErrorHandler?.call(error, stackTrace) ?? false;
}

/// Isolate error handler for current isolate errors
void _setupIsolateErrorHandler() {
if (!_config.captureIsolateErrors) {
return;
}

_isolateErrorHandler.addErrorListener(_posthogIsolateErrorHandler);
}

void _posthogIsolateErrorHandler(dynamic error) {
// Isolate errors come as List<dynamic> with [errorString, stackTraceString]
// See: https://api.dartlang.org/stable/2.7.0/dart-isolate/Isolate/addErrorListener.html
if (error is List && error.length == 2) {
final String errorString = error.first;
final String? stackTraceString = error.last;

final wrappedError = PostHogException(
source: errorString,
mechanism: 'isolateError',
handled: false,
);

final stackTrace = stackTraceString != null
? StackTrace.fromString(stackTraceString)
: null;

_captureException(error: wrappedError, stackTrace: stackTrace);
}
}

Future<void> _captureException({
required PostHogException error,
required StackTrace? stackTrace,
Map<String, Object>? properties,
}) {
return _posthog.captureException(
error: error, stackTrace: stackTrace, properties: properties);
}
}
Loading
Loading