Skip to content
Merged
Show file tree
Hide file tree
Changes from 27 commits
Commits
Show all changes
40 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
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
fd00daf
feat: add async gap franes
ioannisj Oct 30, 2025
42443b4
Revert "feat: add web support"
ioannisj Oct 30, 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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
## Next

- feat: add manual error capture ([#212](https://github.com/PostHog/posthog-flutter/pull/212))
- **BREAKING**: Minimum Dart SDK version bumped to 3.4.0 and Flutter to 3.22.0 (required for `stack_trace` dependency compatibility)

## 5.6.0

- feat: surveys use the new response question id format ([#210](https://github.com/PostHog/posthog-flutter/pull/210))
Expand Down
7 changes: 6 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
.PHONY: formatKotlin formatSwift formatDart checkDart installLinters
.PHONY: format formatKotlin formatSwift formatDart checkDart installLinters test

format: formatSwift formatKotlin formatDart

installLinters:
brew install ktlint
Expand All @@ -19,3 +21,6 @@ checkFormatDart:

analyzeDart:
dart analyze .

test:
flutter test -r expanded
4 changes: 2 additions & 2 deletions android/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ android {
dependencies {
testImplementation 'org.jetbrains.kotlin:kotlin-test'
testImplementation 'org.mockito:mockito-core:5.0.0'
// + Version 3.23.0 and the versions up to 4.0.0, not including 4.0.0 and higher
implementation 'com.posthog:posthog-android:[3.23.0,4.0.0]'
// + Version 3.25.0 and the versions up to 4.0.0, not including 4.0.0 and higher
implementation 'com.posthog:posthog-android:[3.25.0,4.0.0]'
}

testOptions {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import java.util.Date

/** PosthogFlutterPlugin */
class PosthogFlutterPlugin :
Expand Down Expand Up @@ -156,6 +157,9 @@ class PosthogFlutterPlugin :
"flush" -> {
flush(result)
}
"captureException" -> {
captureException(call, result)
}
"close" -> {
close(result)
}
Expand Down Expand Up @@ -532,6 +536,35 @@ class PosthogFlutterPlugin :
}
}

private fun captureException(
call: MethodCall,
result: Result,
) {
try {
val arguments =
call.arguments as? Map<String, Any> ?: run {
result.error("INVALID_ARGUMENTS", "Invalid arguments for captureException", null)
return
}

var properties = arguments.toMutableMap() // make mutable

// Extract timestamp from Flutter
var timestamp: Date? = null
val timestampMs = properties["timestamp"] as? Long
if (timestampMs != null) {
// timestampMs already in UTC milliseconds epoch
timestamp = Date(timestampMs)
properties.remove("timestamp")
}

PostHog.capture("\$exception", properties = properties, timestamp = timestamp)
result.success(null)
} catch (e: Throwable) {
result.error("CAPTURE_EXCEPTION_ERROR", "Failed to capture exception: ${e.message}", null)
}
}

private fun close(result: Result) {
try {
PostHog.close()
Expand Down
162 changes: 162 additions & 0 deletions example/lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import 'dart:isolate';
import 'package:flutter/material.dart';
import 'package:posthog_flutter/posthog_flutter.dart';

Expand All @@ -21,6 +22,28 @@ Future<void> main() async {
runApp(const MyApp());
}

/// This function runs in a separate isolate with its own sandboxed thread, meant to demonstate capturing exceptions from background "threads"
void _backgroundIsolateEntryPoint(SendPort sendPort) async {
await Future.delayed(const Duration(milliseconds: 500));

try {
// Simulate an exception in the background isolate
throw StateError('Background isolate processing failed!');
} catch (e, stack) {
// Send exception data back to main isolate for capture
sendPort.send({
'error': e.toString(),
'errorType': e.runtimeType.toString(),
'stackTrace': stack.toString(),
'properties': {
'test_type': 'background_isolate_exception',
'isolate_name': 'exception-demo-worker',
'button_pressed': 'capture_exception_background',
},
});
}
}

class MyApp extends StatefulWidget {
const MyApp({super.key});

Expand Down Expand Up @@ -240,6 +263,77 @@ class InitialScreenState extends State<InitialScreen> {
child: Text("distinctId"),
)),
const Divider(),
const Padding(
padding: EdgeInsets.all(8.0),
child: Text(
"Error Tracking",
style: TextStyle(fontWeight: FontWeight.bold),
),
),
ElevatedButton(
onPressed: () async {
try {
// Simulate an exception in main isolate
// throw 'a custom error string';
// throw 333;
throw CustomException(
'This is a custom exception with additional context',
code: 'DEMO_ERROR_001',
additionalData: {
'user_action': 'button_press',
'timestamp': DateTime.now().millisecondsSinceEpoch,
'feature_enabled': true,
},
);
} catch (e, stack) {
await Posthog().captureException(
error: e,
stackTrace: stack,
properties: {
'test_type': 'main_isolate_exception',
'button_pressed': 'capture_exception_main',
'exception_category': 'custom',
},
);

if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'Main isolate exception captured successfully! Check PostHog.'),
backgroundColor: Colors.green,
duration: Duration(seconds: 3),
),
);
}
}
},
child: const Text("Capture Exception (Main)"),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.orange,
),
onPressed: () async {
// Capture exception from background isolate
await _captureExceptionFromBackgroundIsolate();
},
child: const Text("Capture Exception (Background)"),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.orange,
),
onPressed: () async {
// Capture exception from background isolate
await Posthog().captureException(
error: 'No Stack Trace Error',
properties: {'test_type': 'no_stack_trace'},
);
},
child: const Text("Capture Exception (No Stack)"),
),
const Divider(),
const Padding(
padding: EdgeInsets.all(8.0),
child: Text(
Expand Down Expand Up @@ -300,6 +394,53 @@ class InitialScreenState extends State<InitialScreen> {
),
);
}

/// Demonstrates exception capture from a background isolate
/// This should show a different thread_id than the main isolate
Future<void> _captureExceptionFromBackgroundIsolate() async {
final receivePort = ReceivePort();

// Spawn a background isolate with a custom name for demonstration
await Isolate.spawn(
_backgroundIsolateEntryPoint,
receivePort.sendPort,
debugName: 'custom-isolate-name-will-be-hashed-as-thread_id',
);

// Wait for the isolate to complete (or timeout after 5 seconds)
final result = await receivePort.first.timeout(
const Duration(seconds: 5),
onTimeout: () => {'type': 'timeout'},
);

if (result is Map<String, dynamic>) {
// Reconstruct the stack trace from the string
final stackTrace = StackTrace.fromString(result['stackTrace']);

// Create a synthetic error with the original error message and type
final syntheticError =
Exception('${result['errorType']}: ${result['error']}');

await Posthog().captureException(
error: syntheticError,
stackTrace: stackTrace,
properties: Map<String, Object>.from(result['properties'] ?? {}),
);

if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'Background isolate exception captured successfully! Check PostHog.'),
backgroundColor: Colors.green,
duration: Duration(seconds: 3),
),
);
}
}

receivePort.close();
}
}

class SecondRoute extends StatefulWidget {
Expand Down Expand Up @@ -391,3 +532,24 @@ class ThirdRoute extends StatelessWidget {
);
}
}

/// Custom exception class for demonstration purposes
class CustomException implements Exception {
final String message;
final String? code;
final Map<String, dynamic>? additionalData;

const CustomException(
this.message, {
this.code,
this.additionalData,
});

@override
String toString() {
if (code != null) {
return 'CustomException($code): $message $additionalData';
}
return 'CustomException: $message $additionalData';
}
}
22 changes: 22 additions & 0 deletions ios/Classes/PosthogFlutterPlugin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,8 @@ public class PosthogFlutterPlugin: NSObject, FlutterPlugin {
unregister(call, result: result)
case "flush":
flush(result)
case "captureException":
captureException(call, result: result)
case "close":
close(result)
case "sendMetaEvent":
Expand Down Expand Up @@ -677,6 +679,26 @@ extension PosthogFlutterPlugin {
result(nil)
}

private func captureException(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
guard let arguments = call.arguments as? [String: Any] else {
result(FlutterError(code: "INVALID_ARGUMENTS", message: "Invalid arguments for captureException", details: nil))
return
}

var properties = arguments // make mutable

// Extract timestamp from Flutter and convert to Date
var timestamp: Date? = nil
if let timestampMs = properties["timestamp"] as? Int64 {
timestamp = Date(timeIntervalSince1970: TimeInterval(timestampMs) / 1000.0)
properties.removeValue(forKey: "timestamp")
}

// Use capture method with timestamp to ensure Flutter timestamp is used
PostHogSDK.shared.capture("$exception", properties: properties, timestamp: timestamp)
result(nil)
}

private func close(_ result: @escaping FlutterResult) {
PostHogSDK.shared.close()
result(nil)
Expand Down
Loading
Loading