-
Notifications
You must be signed in to change notification settings - Fork 11
/
client.dart
851 lines (736 loc) · 28.5 KB
/
client.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
import 'dart:async';
import 'dart:io';
import 'dart:ui';
import 'package:bugsnag_flutter/src/error_factory.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart' show WidgetsFlutterBinding;
import 'callbacks.dart';
import 'config.dart';
import 'enum_utils.dart';
import 'last_run_info.dart';
import 'model.dart';
final _notifier = {
'name': 'Flutter Bugsnag Notifier',
'url': 'https://github.com/bugsnag/bugsnag-flutter',
'version': '2.4.0'
};
abstract class BugsnagClient {
/// An utility error handling function that will send reported errors to
/// Bugsnag as unhandled. The [errorHandler] is suitable for use with
/// common Dart error callbacks such as [runZonedGuarded] or [Future.onError].
void Function(dynamic error, StackTrace? stack) get errorHandler;
/// Sets the user information to be associated with events
Future<void> setUser({String? id, String? email, String? name});
/// Returns the currently set User information.
Future<BugsnagUser> getUser();
/// Bugsnag uses the concept of “contexts” to help display and group your
/// errors. The context represents what was happening in your application
/// at the time an error occurs and is given high visual prominence in
/// the dashboard.
///
/// The "context" can be made to follow your app navigation by using the
/// [BugsnagNavigatorObserver] in your application of `Navigator`:
/// ```dart
/// return MaterialApp(
/// navigatorObservers: [BugsnagNavigatorObserver(setContext: true)],
/// ```
///
/// See also:
/// - [getContext]
/// - [BugsnagNavigatorObserver]
Future<void> setContext(String? context);
/// Bugsnag uses the concept of “contexts” to help display and group your
/// errors. The context represents what was happening in your application
/// at the time an error occurs and is given high visual prominence in
/// the dashboard.
///
/// See also:
/// - [setContext]
/// - [BugsnagNavigatorObserver]
Future<String?> getContext();
/// Leave a "breadcrumb" log message, representing an action that occurred
/// in your app, to aid with debugging.
///
/// [message] is a short label to identify the action that occurred, while
/// [metadata] can contain useful information associated with the action.
///
/// See also:
/// - [getBreadcrumbs]
/// - [BugsnagMetadata.sanitizedMap]
Future<void> leaveBreadcrumb(
String message, {
Map<String, Object>? metadata,
BugsnagBreadcrumbType type = BugsnagBreadcrumbType.manual,
});
/// Returns the current buffer of breadcrumbs that will be sent with captured
/// events. This ordered list represents the most recent breadcrumbs to be
/// captured up to the limit set in [start].
Future<List<BugsnagBreadcrumb>> getBreadcrumbs();
/// Add a single feature flag with an optional variant. If there is an
/// existing feature flag with the same name, it will be overwritten with the
/// new variant.
///
/// See also:
/// - [addFeatureFlags]
/// - [clearFeatureFlag]
/// - [clearFeatureFlags]
Future<void> addFeatureFlag(String name, [String? variant]);
/// Add a collection of feature flags. This has the same effect as calling
/// [addFeatureFlag] for each value passed, but it typically faster when there
/// are more than one `FeatureFlag`.
///
/// See also:
/// - [addFeatureFlag]
/// - [clearFeatureFlag]
/// - [clearFeatureFlags]
Future<void> addFeatureFlags(List<BugsnagFeatureFlag> featureFlags);
/// Remove a single feature flag regardless of its current status. This will
/// stop the specified feature flag from being reported. If the named feature
/// flag does not exist this will have no effect.
///
/// See also:
/// - [addFeatureFlag]
/// - [addFeatureFlags]
/// - [clearFeatureFlags]
Future<void> clearFeatureFlag(String name);
/// Clear all of the feature flags. This will stop all feature flags from
/// being reported.
///
/// See also:
/// - [addFeatureFlag]
/// - [addFeatureFlags]
/// - [clearFeatureFlag]
Future<void> clearFeatureFlags();
/// Adds a map of multiple metadata key-value pairs to the specified section.
/// ```dart
/// bugsnag.addMetadata('account', const {'name': 'Acme. Co.'});
/// ```
///
/// See also:
/// - [BugsnagMetadata.sanitizedMap]
/// - [getMetadata]
/// - [clearMetadata]
Future<void> addMetadata(String section, Map<String, Object> metadata);
/// If [key] is not `null`: removes data with the specified key from the
/// specified section. Otherwise remove all the data from the specified
/// [section].
Future<void> clearMetadata(String section, [String? key]);
/// Returns a map of data in the specified section.
Future<Map<String, Object>?> getMetadata(String section);
/// Starts tracking a new session. You should disable automatic session
/// by setting `autoTrackSessions` to `false` in [start].
///
/// You should call this at the appropriate time in your application when you
/// wish to start a session. Any subsequent errors which occur in your
/// application will still be reported to Bugsnag but will not count towards
/// your application's [stability score](https://docs.bugsnag.com/product/releases/releases-dashboard/#stability-score).
/// This will start a new session even if there is already an existing
/// session; you should call [resumeSession] if you only want to start a
/// session when one doesn't already exist.
///
/// See also:
/// - [pauseSession]
/// - [resumeSession]
Future<void> startSession();
/// Pauses tracking of a session. You should disable automatic session
/// by setting `autoTrackSessions` to `false` in [start].
///
/// You should call this at the appropriate time in your application when you
/// wish to pause a session. Any subsequent errors which occur in your
/// application will still be reported to Bugsnag but will not count towards
/// your application's [stability score](https://docs.bugsnag.com/product/releases/releases-dashboard/#stability-score).
/// This can be advantageous if, for example, you do not wish the stability
/// score to include crashes in a background service.
///
/// See also:
/// - [startSession]
/// - [resumeSession]
Future<void> pauseSession();
/// Resumes a session which has previously been paused, or starts a new
/// session if none exists. If a session has already been resumed or started
/// and has not been paused, calling this method will have no effect.
/// You should disable automatic session by setting `autoTrackSessions`
/// to `false` in [start] if you call this method.
///
/// It's important to note that sessions are stored in memory for the lifetime
/// of the application process and are not persisted on disk. Therefore
/// calling this method on app startup would start a new session, rather
/// than continuing any previous session.
///
/// You should call this at the appropriate time in your application when you
/// wish to resume a previously started session. Any subsequent errors which
/// occur in your application will still be reported to Bugsnag but will not
/// count towards your application's [stability score](https://docs.bugsnag.com/product/releases/releases-dashboard/#stability-score).
///
/// See also:
/// - [startSession]
/// - [pauseSession]
Future<bool> resumeSession();
/// Informs Bugsnag that the application has finished launching. Once this
/// has resolved [BugsnagAppWithState.isLaunching] will always be false in any new
/// error reports, and synchronous delivery will not be attempted on the next
/// launch for any fatal crashes.
Future<void> markLaunchCompleted();
/// Retrieves information about the last launch of the application, if it
/// has been run before.
///
/// For example, this allows checking whether the app crashed on its last
/// launch, which could be used to perform conditional behaviour to recover
/// from crashes, such as clearing the app data cache.
Future<BugsnagLastRunInfo?> getLastRunInfo();
/// Notify Bugsnag of a handled exception.
///
/// The [callback] can be specified to modify the generated event before it
/// is delivered to Bugsnag.
Future<void> notify(
dynamic error,
StackTrace? stackTrace, {
BugsnagOnErrorCallback? callback,
});
/// Add a "on error" callback, to execute code at the point where an error
/// report is captured in Bugsnag.
///
/// You can use this to add or modify information attached to an [event](BugsnagEvent)
/// before it is sent to your dashboard. You can also return `false` from any
/// callback to prevent delivery.
///
/// ```dart
/// bugsnag.addOnError((event) {
/// event.severity = Severity.info;
/// return true;
/// });
/// ```
///
/// "on error" callbacks added here are only triggered for events originating
/// in Dart and will always be triggered before "on error" callbacks added
/// in the native layer (on Android and iOS).
void addOnError(BugsnagOnErrorCallback onError);
/// Removes a previously added "on error" callback.
void removeOnError(BugsnagOnErrorCallback onError);
}
class DelegateClient implements BugsnagClient {
BugsnagClient? _client;
BugsnagClient get client {
final localClient = _client;
if (localClient == null) {
throw Exception(
'You must start or attach bugsnag before calling any other methods');
}
return localClient;
}
set client(BugsnagClient client) {
_client = client;
}
@override
void Function(dynamic error, StackTrace? stack) get errorHandler =>
client.errorHandler;
@override
Future<BugsnagUser> getUser() => client.getUser();
@override
Future<void> setUser({String? id, String? email, String? name}) =>
client.setUser(id: id, email: email, name: name);
@override
Future<void> setContext(String? context) => client.setContext(context);
@override
Future<String?> getContext() => client.getContext();
@override
Future<void> leaveBreadcrumb(
String message, {
Map<String, Object>? metadata,
BugsnagBreadcrumbType type = BugsnagBreadcrumbType.manual,
}) =>
client.leaveBreadcrumb(message, metadata: metadata, type: type);
@override
Future<List<BugsnagBreadcrumb>> getBreadcrumbs() => client.getBreadcrumbs();
@override
Future<void> addFeatureFlag(String name, [String? variant]) =>
client.addFeatureFlag(name, variant);
@override
Future<void> addFeatureFlags(List<BugsnagFeatureFlag> featureFlags) =>
client.addFeatureFlags(featureFlags);
@override
Future<void> clearFeatureFlag(String name) => client.clearFeatureFlag(name);
@override
Future<void> clearFeatureFlags() => client.clearFeatureFlags();
@override
Future<void> addMetadata(String section, Map<String, Object> metadata) =>
client.addMetadata(section, metadata);
@override
Future<void> clearMetadata(String section, [String? key]) =>
client.clearMetadata(section, key);
@override
Future<Map<String, Object>?> getMetadata(String section) =>
client.getMetadata(section);
@override
Future<void> startSession() => client.startSession();
@override
Future<void> pauseSession() => client.pauseSession();
@override
Future<bool> resumeSession() => client.resumeSession();
@override
Future<void> markLaunchCompleted() => client.markLaunchCompleted();
@override
Future<BugsnagLastRunInfo?> getLastRunInfo() => client.getLastRunInfo();
@override
Future<void> notify(
dynamic error,
StackTrace? stackTrace, {
BugsnagOnErrorCallback? callback,
}) =>
client.notify(error, stackTrace, callback: callback);
@override
void addOnError(BugsnagOnErrorCallback onError) => client.addOnError(onError);
@override
void removeOnError(BugsnagOnErrorCallback onError) =>
client.removeOnError(onError);
}
class ChannelClient implements BugsnagClient {
FlutterExceptionHandler? _previousFlutterOnError;
ChannelClient(bool autoDetectErrors) {
if (autoDetectErrors) {
// as ChannelClient is the only implementation that can run within the
// same Isolate as Flutter, we install the FlutterError handler here
_previousFlutterOnError = FlutterError.onError;
FlutterError.onError = _onFlutterError;
}
}
static const MethodChannel _channel =
MethodChannel('com.bugsnag/client', JSONMethodCodec());
final CallbackCollection<BugsnagEvent> _onErrorCallbacks = {};
@override
void Function(dynamic error, StackTrace? stack) get errorHandler =>
_notifyUnhandled;
@override
Future<BugsnagUser> getUser() async =>
BugsnagUser.fromJson(await _channel.invokeMethod('getUser'));
@override
Future<void> setUser({String? id, String? email, String? name}) =>
_channel.invokeMethod(
'setUser',
BugsnagUser(id: id, email: email, name: name),
);
@override
Future<void> setContext(String? context) =>
_channel.invokeMethod('setContext', {'context': context});
@override
Future<String?> getContext() => _channel.invokeMethod('getContext');
@override
Future<void> leaveBreadcrumb(
String message, {
Map<String, Object>? metadata,
BugsnagBreadcrumbType type = BugsnagBreadcrumbType.manual,
}) async {
final crumb = BugsnagBreadcrumb(message, type: type, metadata: metadata);
await _channel.invokeMethod('leaveBreadcrumb', crumb);
}
@override
Future<List<BugsnagBreadcrumb>> getBreadcrumbs() async =>
List.from((await _channel.invokeMethod('getBreadcrumbs') as List)
.map((e) => BugsnagBreadcrumb.fromJson(e)));
@override
Future<void> addFeatureFlag(String name, [String? variant]) => _channel
.invokeMethod('addFeatureFlags', [BugsnagFeatureFlag(name, variant)]);
@override
Future<void> addFeatureFlags(List<BugsnagFeatureFlag> featureFlags) =>
_channel.invokeMethod('addFeatureFlags', featureFlags);
@override
Future<void> clearFeatureFlag(String name) =>
_channel.invokeMethod('clearFeatureFlag', {'name': name});
@override
Future<void> clearFeatureFlags() =>
_channel.invokeMethod('clearFeatureFlags');
@override
Future<void> addMetadata(String section, Map<String, Object> metadata) =>
_channel.invokeMethod('addMetadata', {
'section': section,
'metadata': BugsnagMetadata.sanitizedMap(metadata),
});
@override
Future<void> clearMetadata(String section, [String? key]) =>
_channel.invokeMethod('clearMetadata', {
'section': section,
if (key != null) 'key': key,
});
@override
Future<Map<String, Object>?> getMetadata(String section) async {
final metadata = await _channel.invokeMethod(
'getMetadata',
{'section': section},
);
return (metadata != null) ? Map.from(metadata).cast() : null;
}
@override
Future<void> startSession() => _channel.invokeMethod('startSession');
@override
Future<void> pauseSession() => _channel.invokeMethod('pauseSession');
@override
Future<bool> resumeSession() async =>
await _channel.invokeMethod('resumeSession') as bool;
@override
Future<void> markLaunchCompleted() =>
_channel.invokeMethod('markLaunchCompleted');
@override
Future<BugsnagLastRunInfo?> getLastRunInfo() async {
final json = await _channel.invokeMethod('getLastRunInfo');
return (json == null) ? null : BugsnagLastRunInfo.fromJson(json);
}
@override
void addOnError(BugsnagOnErrorCallback onError) {
_onErrorCallbacks.add(onError);
}
@override
void removeOnError(BugsnagOnErrorCallback onError) {
_onErrorCallbacks.remove(onError);
}
void _onFlutterError(FlutterErrorDetails details) {
_notifyInternal(details.exception, true, details, details.stack, null);
_previousFlutterOnError?.call(details);
}
Future<void> _notifyInternal(
dynamic error,
bool unhandled,
FlutterErrorDetails? details,
StackTrace? stackTrace,
BugsnagOnErrorCallback? callback,
) async {
final errorPayload =
BugsnagErrorFactory.instance.createError(error, stackTrace);
final event = await _createEvent(
errorPayload,
details: details,
unhandled: unhandled,
deliver: _onErrorCallbacks.isEmpty && callback == null,
);
if (event == null) {
return;
}
if (!await _onErrorCallbacks.dispatch(event)) {
// callback rejected the payload - so we don't deliver it
return;
}
if (callback != null && !await callback.invokeSafely(event)) {
// callback rejected the payload - so we don't deliver it
return;
}
await _deliverEvent(event);
}
@override
Future<void> notify(
dynamic error,
StackTrace? stackTrace, {
BugsnagOnErrorCallback? callback,
}) {
return _notifyInternal(error, false, null, stackTrace, callback);
}
void _notifyUnhandled(dynamic error, StackTrace? stackTrace) {
_notifyInternal(error, true, null, stackTrace, null);
}
/// Create an Event by having it built by the native notifier,
/// if [deliver] is `true` return `null` and schedule the `Event` for immediate
/// delivery. If [deliver] is `false` then the `Event` is only constructed
/// and returned to be processed by the Flutter notifier.
Future<BugsnagEvent?> _createEvent(
BugsnagError error, {
FlutterErrorDetails? details,
required bool unhandled,
required bool deliver,
}) async {
final buildID = error.stacktrace.first.codeIdentifier;
final errorInfo = details?.informationCollector?.call() ?? [];
final errorContext = details?.context?.toDescription();
final errorLibrary = details?.library;
// SchedulerBinding.instance is nullable in Flutter <3.0.0
// ignore: unnecessary_cast
final schedulerBinding = SchedulerBinding.instance as SchedulerBinding?;
final lifecycleState = schedulerBinding?.lifecycleState.toString();
final metadata = {
if (buildID != null) 'buildID': buildID,
if (errorContext != null) 'errorContext': errorContext,
if (errorLibrary != null) 'errorLibrary': errorLibrary,
if (errorInfo.isNotEmpty)
'errorInformation':
(StringBuffer()..writeAll(errorInfo, '\n')).toString(),
'defaultRouteName': PlatformDispatcher.instance.defaultRouteName,
'initialLifecycleState':
PlatformDispatcher.instance.initialLifecycleState,
if (lifecycleState != null) 'lifecycleState': lifecycleState,
};
final eventJson = await _channel.invokeMethod(
'createEvent',
{
'error': error,
'flutterMetadata': metadata,
'unhandled': unhandled,
'deliver': deliver
},
);
if (eventJson != null) {
return BugsnagEvent.fromJson(eventJson);
}
return null;
}
Future<void> _deliverEvent(BugsnagEvent event) =>
_channel.invokeMethod('deliverEvent', event);
}
/// The primary `Client`. Typically this class is not accessed directly, and
/// is instead accessed using the [bugsnag] global:
///
/// ```dart
/// Future<void> main() => bugsnag.start(
/// apiKey: 'your-api-key',
/// runApp: () => runApp(MyApplication()),
/// );
/// ```
///
/// See also:
/// - [start]
class Bugsnag extends BugsnagClient with DelegateClient {
Bugsnag._internal();
/// Attach Bugsnag to an already initialised native notifier, optionally
/// adding to its existing configuration. Use [start] if your application
/// is entirely built in Flutter.
///
/// Typical hybrid Flutter applications with Bugsnag will start with
/// ```dart
/// Future<void> main() => bugsnag.attach(
/// runApp: () => runApp(MyApplication()),
/// // other configuration here
/// );
/// ```
///
/// Use this method to initialize Flutter when developing a Hybrid app,
/// where Bugsnag is being started by the native part of the app. For more
/// information on starting Bugsnag natively, see our platform guides for:
///
/// - Android: <https://docs.bugsnag.com/platforms/android/>
/// - iOS: <https://docs.bugsnag.com/platforms/ios/>
///
/// See also:
///
/// - [start]
/// - [setUser]
/// - [setContext]
/// - [addFeatureFlags]
/// - [addOnError]
Future<void> attach({
FutureOr<void> Function()? runApp,
List<BugsnagOnErrorCallback> onError = const [],
}) async {
// make sure we can use Channels before calling runApp
_runWithErrorDetection(
true,
() => WidgetsFlutterBinding.ensureInitialized(),
);
final result = await ChannelClient._channel.invokeMethod('attach', {
'notifier': _notifier,
});
final autoDetectErrors =
result['config']['enabledErrorTypes']['dartErrors'] as bool;
final client = ChannelClient(autoDetectErrors);
client._onErrorCallbacks.addAll(onError);
this.client = client;
_runWithErrorDetection(
autoDetectErrors,
() => runApp?.call(),
);
}
/// Initialize the Bugsnag notifier with the configuration options specified.
/// Use [attach] if you are building a Hybrid application where Bugsnag
/// is initialised by the Native layer.
///
/// [start] will pick up any native configuration options that are specified.
///
/// Typical Flutter-only applications with Bugsnag will start with:
/// ```dart
/// Future<void> main() => bugsnag.start(
/// apiKey: 'your-api-key',
/// runApp: () => runApp(MyApplication()),
/// );
/// ```
///
/// See also:
///
/// - [attach]
/// - [setUser]
/// - [setContext]
/// - [addFeatureFlags]
/// - [addOnError]
Future<void> start({
String? apiKey,
FutureOr<void> Function()? runApp,
BugsnagUser? user,
bool persistUser = true,
String? context,
String? appType,
String? appVersion,
String? bundleVersion,
String? releaseStage,
BugsnagEnabledErrorTypes enabledErrorTypes = BugsnagEnabledErrorTypes.all,
BugsnagEndpointConfiguration endpoints =
BugsnagEndpointConfiguration.bugsnag,
int maxBreadcrumbs = 50,
int maxPersistedSessions = 128,
int maxPersistedEvents = 32,
int maxStringValueLength = 10000,
bool autoTrackSessions = true,
bool autoDetectErrors = true,
BugsnagThreadSendPolicy sendThreads = BugsnagThreadSendPolicy.always,
int launchDurationMillis = 5000,
bool sendLaunchCrashesSynchronously = true,
int appHangThresholdMillis = appHangThresholdFatalOnly,
Set<String> redactedKeys = const {'password'},
Set<String> discardClasses = const {},
Set<String>? enabledReleaseStages,
Set<BugsnagEnabledBreadcrumbType>? enabledBreadcrumbTypes,
BugsnagProjectPackages projectPackages =
const BugsnagProjectPackages.withDefaults({}),
Map<String, Map<String, Object>>? metadata,
List<BugsnagFeatureFlag>? featureFlags,
List<BugsnagOnErrorCallback> onError = const [],
Set<BugsnagTelemetryType>? telemetry,
Directory? persistenceDirectory,
int? versionCode,
}) async {
final detectDartErrors =
autoDetectErrors && enabledErrorTypes.unhandledDartExceptions;
// guarding WidgetsFlutterBinding.ensureInitialized() catches
// async errors within the Flutter app
_runWithErrorDetection(
detectDartErrors,
() => WidgetsFlutterBinding.ensureInitialized(),
);
if (projectPackages._includeDefaults) {
projectPackages += BugsnagProjectPackages.only(_findProjectPackages());
}
await ChannelClient._channel.invokeMethod('start', <String, dynamic>{
if (apiKey != null) 'apiKey': apiKey,
if (user != null) 'user': user,
'persistUser': persistUser,
if (context != null) 'context': context,
if (appType != null) 'appType': appType,
if (appVersion != null) 'appVersion': appVersion,
if (bundleVersion != null) 'bundleVersion': bundleVersion,
if (releaseStage != null) 'releaseStage': releaseStage,
'enabledErrorTypes': enabledErrorTypes,
'endpoints': endpoints,
'maxBreadcrumbs': maxBreadcrumbs,
'maxPersistedSessions': maxPersistedSessions,
'maxPersistedEvents': maxPersistedEvents,
'maxStringValueLength': maxStringValueLength,
'autoTrackSessions': autoTrackSessions,
'autoDetectErrors': autoDetectErrors,
'sendThreads': sendThreads.toName(),
'launchDurationMillis': launchDurationMillis,
'sendLaunchCrashesSynchronously': sendLaunchCrashesSynchronously,
'appHangThresholdMillis': appHangThresholdMillis,
'redactedKeys': List<String>.from(redactedKeys),
'discardClasses': List<String>.from(discardClasses),
if (enabledReleaseStages != null)
'enabledReleaseStages': enabledReleaseStages.toList(),
'enabledBreadcrumbTypes':
(enabledBreadcrumbTypes ?? BugsnagEnabledBreadcrumbType.values)
.map((e) => e.toName())
.toList(),
'projectPackages': projectPackages,
if (metadata != null) 'metadata': BugsnagMetadata(metadata),
'featureFlags': featureFlags,
'notifier': _notifier,
'telemetry': (telemetry ?? BugsnagTelemetryType.values)
.map((e) => e.toName())
.toList(),
if (persistenceDirectory != null)
'persistenceDirectory': persistenceDirectory.absolute.path,
if (versionCode != null) 'versionCode': versionCode,
});
final client = ChannelClient(detectDartErrors);
client._onErrorCallbacks.addAll(onError);
this.client = client;
if (autoTrackSessions) {
await resumeSession().onError((error, stackTrace) => true);
}
_runWithErrorDetection(detectDartErrors, () => runApp?.call());
}
void _runWithErrorDetection(
bool errorDetectionEnabled,
FutureOr<void> Function() block,
) async {
if (errorDetectionEnabled) {
await runZonedGuarded(() async {
await block();
}, _reportZonedError);
} else {
await block();
}
}
static const int appHangThresholdFatalOnly = 2147483647;
/// Safely report an error that occurred within a guardedZone - if attached
/// to a [BugsnagClient] then use its [BugsnagClient.errorHandler], otherwise push the error
/// upwards using [Zone.handleUncaughtError]
void _reportZonedError(dynamic error, StackTrace stackTrace) {
if (_client != null) {
errorHandler(error, stackTrace);
} else {
Zone.current.handleUncaughtError(error, stackTrace);
}
}
static Set<String> _findProjectPackages() {
try {
final frames = StackFrame.fromStackTrace(StackTrace.current);
final lastBugsnag = frames.lastIndexWhere((f) =>
f.packageScheme == 'package' && f.package == 'bugsnag_flutter');
if (lastBugsnag != -1 && lastBugsnag < frames.length) {
final package = frames[lastBugsnag + 1].package;
if (package.isNotEmpty && package != 'null') {
return {package};
}
}
} catch (e) {
// deliberately ignored, we return null
}
return const <String>{};
}
}
/// In order to determine where a crash happens Bugsnag needs to know which
/// packages you consider to be part of your app (as opposed to a library).
///
/// By default this is set according to the underlying platform (e.g. Android)
/// and an attempt is made to discover the Dart package your app uses.
/// This detection *will not work* if you build using `--split-debug-info`.
///
/// See also:
/// - [Bugsnag.start]
/// - [BugsnagProjectPackages.defaults]
class BugsnagProjectPackages {
final bool _includeDefaults;
final Set<String> _packageNames;
const BugsnagProjectPackages._internal(
this._packageNames,
this._includeDefaults,
);
/// Specify the exact list of package names to consider as part of the
/// project. This should include packages from both Dart and any Java packages
/// your application uses on Android.
///
/// This does not include any [defaults](ProjectPackages.withDefaults).
const BugsnagProjectPackages.only(Set<String> packageNames)
: this._internal(packageNames, false);
/// Combine the given set of `packageNames` with the default packages.
/// This is useful when you are using `--split-debug-info` and so need to
/// specify your Dart packages in [Bugsnag.start].
///
/// See also:
/// - [Android Configuration.projectPackages](https://docs.bugsnag.com/platforms/android/configuration-options/#projectpackages)
const BugsnagProjectPackages.withDefaults(Set<String> additionalPackageNames)
: this._internal(additionalPackageNames, true);
operator +(BugsnagProjectPackages other) => BugsnagProjectPackages._internal(
_packageNames.union(other._packageNames),
_includeDefaults || other._includeDefaults);
dynamic toJson() => <String, dynamic>{
'includeDefaults': _includeDefaults,
'packageNames': List.from(_packageNames),
};
}
/// Primary access to the Bugsnag API, most calls to Bugsnag will start here
final Bugsnag bugsnag = Bugsnag._internal();