-
Notifications
You must be signed in to change notification settings - Fork 205
/
Client.java
1336 lines (1185 loc) · 45.8 KB
/
Client.java
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
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.bugsnag.android;
import static com.bugsnag.android.ConfigFactory.MF_BUILD_UUID;
import static com.bugsnag.android.MapUtils.getStringFromMap;
import android.app.Activity;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.concurrent.RejectedExecutionException;
/**
* A Bugsnag Client instance allows you to use Bugsnag in your Android app.
* Typically you'd instead use the static access provided in the Bugsnag class.
* <p/>
* Example usage:
* <p/>
* Client client = new Client(this, "your-api-key");
* client.notify(new RuntimeException("something broke!"));
*
* @see Bugsnag
*/
@SuppressWarnings("checkstyle:JavadocTagContinuationIndentation")
public class Client extends Observable implements Observer {
private static final boolean BLOCKING = true;
private static final String SHARED_PREF_KEY = "com.bugsnag.android";
private static final String USER_ID_KEY = "user.id";
private static final String USER_NAME_KEY = "user.name";
private static final String USER_EMAIL_KEY = "user.email";
@NonNull
protected final Configuration config;
final Context appContext;
@NonNull
protected final DeviceData deviceData;
@NonNull
protected final AppData appData;
@NonNull
final Breadcrumbs breadcrumbs;
@NonNull
private final User user = new User();
@NonNull
protected final ErrorStore errorStore;
final SessionStore sessionStore;
private final EventReceiver eventReceiver;
final SessionTracker sessionTracker;
SharedPreferences sharedPrefs;
/**
* Initialize a Bugsnag client
*
* @param androidContext an Android context, usually <code>this</code>
*/
public Client(@NonNull Context androidContext) {
this(androidContext, null, true);
}
/**
* Initialize a Bugsnag client
*
* @param androidContext an Android context, usually <code>this</code>
* @param apiKey your Bugsnag API key from your Bugsnag dashboard
*/
public Client(@NonNull Context androidContext, @Nullable String apiKey) {
this(androidContext, apiKey, true);
}
/**
* Initialize a Bugsnag client
*
* @param androidContext an Android context, usually <code>this</code>
* @param apiKey your Bugsnag API key from your Bugsnag dashboard
* @param enableExceptionHandler should we automatically handle uncaught exceptions?
*/
public Client(@NonNull Context androidContext,
@Nullable String apiKey,
boolean enableExceptionHandler) {
this(androidContext,
ConfigFactory.createNewConfiguration(androidContext, apiKey, enableExceptionHandler));
}
/**
* Initialize a Bugsnag client
*
* @param androidContext an Android context, usually <code>this</code>
* @param configuration a configuration for the Client
*/
public Client(@NonNull Context androidContext, @NonNull Configuration configuration) {
warnIfNotAppContext(androidContext);
appContext = androidContext.getApplicationContext();
config = configuration;
sessionStore = new SessionStore(config, appContext);
ConnectivityManager cm =
(ConnectivityManager) appContext.getSystemService(Context.CONNECTIVITY_SERVICE);
//noinspection ConstantConditions
if (configuration.getDelivery() == null) {
configuration.setDelivery(new DefaultDelivery(cm));
}
sessionTracker =
new SessionTracker(configuration, this, sessionStore);
eventReceiver = new EventReceiver(this);
// Set up and collect constant app and device diagnostics
sharedPrefs = appContext.getSharedPreferences(SHARED_PREF_KEY, Context.MODE_PRIVATE);
appData = new AppData(this);
deviceData = new DeviceData(this);
// Set up breadcrumbs
breadcrumbs = new Breadcrumbs();
// Set sensible defaults
setProjectPackages(appContext.getPackageName());
String deviceId = getStringFromMap("id", deviceData.getDeviceData());
if (config.getPersistUserBetweenSessions()) {
// Check to see if a user was stored in the SharedPreferences
user.setId(sharedPrefs.getString(USER_ID_KEY, deviceId));
user.setName(sharedPrefs.getString(USER_NAME_KEY, null));
user.setEmail(sharedPrefs.getString(USER_EMAIL_KEY, null));
} else {
user.setId(deviceId);
}
if (appContext instanceof Application) {
Application application = (Application) appContext;
application.registerActivityLifecycleCallbacks(sessionTracker);
} else {
Logger.warn("Bugsnag is unable to setup automatic activity lifecycle "
+ "breadcrumbs on API Levels below 14.");
}
// populate from manifest (in the case where the constructor was called directly by the
// User or no UUID was supplied)
if (config.getBuildUUID() == null) {
String buildUuid = null;
try {
PackageManager packageManager = appContext.getPackageManager();
String packageName = appContext.getPackageName();
ApplicationInfo ai =
packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
buildUuid = ai.metaData.getString(MF_BUILD_UUID);
} catch (Exception ignore) {
Logger.warn("Bugsnag is unable to read build UUID from manifest.");
}
if (buildUuid != null) {
config.setBuildUUID(buildUuid);
}
}
// Create the error store that is used in the exception handler
errorStore = new ErrorStore(config, appContext);
// Install a default exception handler with this client
if (config.getEnableExceptionHandler()) {
enableExceptionHandler();
}
// register a receiver for automatic breadcrumbs
try {
Async.run(new Runnable() {
@Override
public void run() {
appContext.registerReceiver(eventReceiver, EventReceiver.getIntentFilter());
appContext.registerReceiver(new ConnectivityChangeReceiver(),
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
});
} catch (RejectedExecutionException ex) {
Logger.warn("Failed to register for automatic breadcrumb broadcasts", ex);
}
config.addObserver(this);
boolean isNotProduction = !AppData.RELEASE_STAGE_PRODUCTION.equals(
appData.guessReleaseStage());
Logger.setEnabled(isNotProduction);
// Flush any on-disk errors
errorStore.flushOnLaunch();
}
private class ConnectivityChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
boolean retryReports = networkInfo != null && networkInfo.isConnectedOrConnecting();
if (retryReports) {
errorStore.flushAsync();
}
}
}
public void notifyBugsnagObservers(@NonNull NotifyType type) {
setChanged();
super.notifyObservers(type.getValue());
}
@Override
public void update(Observable observable, Object arg) {
if (arg instanceof Integer) {
NotifyType type = NotifyType.fromInt((Integer) arg);
if (type != null) {
notifyBugsnagObservers(type);
}
}
}
/**
* Manually starts tracking a new session.
*
* Automatic session tracking can be enabled via
* {@link Configuration#setAutoCaptureSessions(boolean)}, which will automatically create a new
* session everytime the app enters the foreground.
*/
public void startSession() {
sessionTracker.startNewSession(new Date(), user, false);
}
/**
* Starts tracking a new session only if no sessions have yet been tracked
*
* This is an integration point for custom libraries implementing automatic session capture
* which differs from the default activity-based initialization.
*/
public void startFirstSession(Activity activity) {
sessionTracker.startFirstSession(activity);
}
/**
* Set the application version sent to Bugsnag. By default we'll pull this
* from your AndroidManifest.xml
*
* @param appVersion the app version to send
*/
public void setAppVersion(String appVersion) {
config.setAppVersion(appVersion);
}
/**
* Gets the context to be sent to Bugsnag.
*
* @return Context
*/
public String getContext() {
return config.getContext();
}
/**
* Set the context sent to Bugsnag. By default we'll attempt to detect the
* name of the top-most activity at the time of a report, and use this
* as the context, but sometime this is not possible.
*
* @param context set what was happening at the time of a crash
*/
public void setContext(String context) {
config.setContext(context);
}
/**
* Set the endpoint to send data to. By default we'll send reports to
* the standard https://notify.bugsnag.com endpoint, but you can override
* this if you are using Bugsnag Enterprise to point to your own Bugsnag
* endpoint.
*
* @param endpoint the custom endpoint to send report to
* @deprecated use {@link com.bugsnag.android.Configuration#setEndpoints(String, String)}
* instead.
*/
@Deprecated
public void setEndpoint(String endpoint) {
config.setEndpoint(endpoint);
}
/**
* Set the buildUUID to your own value. This is used to identify proguard
* mapping files in the case that you publish multiple different apps with
* the same appId and versionCode. The default value is read from the
* com.bugsnag.android.BUILD_UUID meta-data field in your app manifest.
*
* @param buildUuid the buildUuid.
*/
@SuppressWarnings("checkstyle:AbbreviationAsWordInName")
public void setBuildUUID(final String buildUuid) {
config.setBuildUUID(buildUuid);
}
/**
* Set which keys should be filtered when sending metaData to Bugsnag.
* Use this when you want to ensure sensitive information, such as passwords
* or credit card information is stripped from metaData you send to Bugsnag.
* Any keys in metaData which contain these strings will be marked as
* [FILTERED] when send to Bugsnag.
* <p/>
* For example:
* <p/>
* client.setFilters("password", "credit_card");
*
* @param filters a list of keys to filter from metaData
*/
public void setFilters(String... filters) {
config.setFilters(filters);
}
/**
* Set which exception classes should be ignored (not sent) by Bugsnag.
* <p/>
* For example:
* <p/>
* client.setIgnoreClasses("java.lang.RuntimeException");
*
* @param ignoreClasses a list of exception classes to ignore
*/
public void setIgnoreClasses(String... ignoreClasses) {
config.setIgnoreClasses(ignoreClasses);
}
/**
* Set for which releaseStages errors should be sent to Bugsnag.
* Use this to stop errors from development builds being sent.
* <p/>
* For example:
* <p/>
* client.setNotifyReleaseStages("production");
*
* @param notifyReleaseStages a list of releaseStages to notify for
* @see #setReleaseStage
*/
public void setNotifyReleaseStages(String... notifyReleaseStages) {
config.setNotifyReleaseStages(notifyReleaseStages);
}
/**
* Set which packages should be considered part of your application.
* Bugsnag uses this to help with error grouping, and stacktrace display.
* <p/>
* For example:
* <p/>
* client.setProjectPackages("com.example.myapp");
* <p/>
* By default, we'll mark the current package name as part of you app.
*
* @param projectPackages a list of package names
*/
public void setProjectPackages(String... projectPackages) {
config.setProjectPackages(projectPackages);
}
/**
* Set the current "release stage" of your application.
* By default, we'll set this to "development" for debug builds and
* "production" for non-debug builds.
*
* @param releaseStage the release stage of the app
* @see #setNotifyReleaseStages
*/
public void setReleaseStage(String releaseStage) {
config.setReleaseStage(releaseStage);
Logger.setEnabled(!AppData.RELEASE_STAGE_PRODUCTION.equals(releaseStage));
}
/**
* Set whether to send thread-state with report.
* By default, this will be true.
*
* @param sendThreads should we send thread-state with report?
*/
public void setSendThreads(boolean sendThreads) {
config.setSendThreads(sendThreads);
}
/**
* Sets whether or not Bugsnag should automatically capture and report User sessions whenever
* the app enters the foreground.
* <p>
* By default this behavior is disabled.
*
* @param autoCapture whether sessions should be captured automatically
*/
public void setAutoCaptureSessions(boolean autoCapture) {
config.setAutoCaptureSessions(autoCapture);
if (autoCapture) { // track any existing sessions
sessionTracker.onAutoCaptureEnabled();
}
}
/**
* Set details of the user currently using your application.
* You can search for this information in your Bugsnag dashboard.
* <p/>
* For example:
* <p/>
* client.setUser("12345", "james@example.com", "James Smith");
*
* @param id a unique identifier of the current user (defaults to a unique id)
* @param email the email address of the current user
* @param name the name of the current user
*/
public void setUser(String id, String email, String name) {
setUserId(id);
setUserEmail(email);
setUserName(name);
}
/**
* Retrieves details of the user currently using your application.
* You can search for this information in your Bugsnag dashboard.
*
* @return the current user
*/
@NonNull
public User getUser() {
return user;
}
@NonNull
@InternalApi
public Collection<Breadcrumb> getBreadcrumbs() {
return new ArrayList<>(breadcrumbs.store);
}
@NonNull
@InternalApi
public AppData getAppData() {
return appData;
}
@NonNull
@InternalApi
public DeviceData getDeviceData() {
return deviceData;
}
/**
* Removes the current user data and sets it back to defaults
*/
public void clearUser() {
user.setId(getStringFromMap("id", deviceData.getDeviceData()));
user.setEmail(null);
user.setName(null);
SharedPreferences sharedPref =
appContext.getSharedPreferences(SHARED_PREF_KEY, Context.MODE_PRIVATE);
sharedPref.edit()
.remove(USER_ID_KEY)
.remove(USER_EMAIL_KEY)
.remove(USER_NAME_KEY)
.apply();
notifyBugsnagObservers(NotifyType.USER);
}
/**
* Set a unique identifier for the user currently using your application.
* By default, this will be an automatically generated unique id
* You can search for this information in your Bugsnag dashboard.
*
* @param id a unique identifier of the current user
*/
public void setUserId(String id) {
setUserId(id, true);
}
/**
* Sets the user ID with the option to not notify any NDK components of the change
*
* @param id a unique identifier of the current user
* @param notify whether or not to notify NDK components
*/
void setUserId(String id, boolean notify) {
user.setId(id);
if (config.getPersistUserBetweenSessions()) {
storeInSharedPrefs(USER_ID_KEY, id);
}
if (notify) {
notifyBugsnagObservers(NotifyType.USER);
}
}
/**
* Set the email address of the current user.
* You can search for this information in your Bugsnag dashboard.
*
* @param email the email address of the current user
*/
public void setUserEmail(String email) {
setUserEmail(email, true);
}
/**
* Sets the user email with the option to not notify any NDK components of the change
*
* @param email the email address of the current user
* @param notify whether or not to notify NDK components
*/
void setUserEmail(String email, boolean notify) {
user.setEmail(email);
if (config.getPersistUserBetweenSessions()) {
storeInSharedPrefs(USER_EMAIL_KEY, email);
}
if (notify) {
notifyBugsnagObservers(NotifyType.USER);
}
}
/**
* Set the name of the current user.
* You can search for this information in your Bugsnag dashboard.
*
* @param name the name of the current user
*/
public void setUserName(String name) {
setUserName(name, true);
}
/**
* Sets the user name with the option to not notify any NDK components of the change
*
* @param name the name of the current user
* @param notify whether or not to notify NDK components
*/
void setUserName(String name, boolean notify) {
user.setName(name);
if (config.getPersistUserBetweenSessions()) {
storeInSharedPrefs(USER_NAME_KEY, name);
}
if (notify) {
notifyBugsnagObservers(NotifyType.USER);
}
}
DeliveryCompat getAndSetDeliveryCompat() {
Delivery current = config.getDelivery();
if (current instanceof DeliveryCompat) {
return (DeliveryCompat)current;
} else {
DeliveryCompat compat = new DeliveryCompat();
config.setDelivery(compat);
return compat;
}
}
@SuppressWarnings("ConstantConditions")
@Deprecated
void setErrorReportApiClient(@NonNull ErrorReportApiClient errorReportApiClient) {
if (errorReportApiClient == null) {
throw new IllegalArgumentException("ErrorReportApiClient cannot be null.");
}
DeliveryCompat compat = getAndSetDeliveryCompat();
compat.errorReportApiClient = errorReportApiClient;
}
@SuppressWarnings("ConstantConditions")
@Deprecated
void setSessionTrackingApiClient(@NonNull SessionTrackingApiClient apiClient) {
if (apiClient == null) {
throw new IllegalArgumentException("SessionTrackingApiClient cannot be null.");
}
DeliveryCompat compat = getAndSetDeliveryCompat();
compat.sessionTrackingApiClient = apiClient;
}
/**
* Add a "before notify" callback, to execute code before every
* report to Bugsnag.
* <p/>
* You can use this to add or modify information attached to an error
* before it is sent to your dashboard. You can also return
* <code>false</code> from any callback to halt execution.
* <p/>
* For example:
* <p/>
* client.beforeNotify(new BeforeNotify() {
* public boolean run(Error error) {
* error.setSeverity(Severity.INFO);
* return true;
* }
* })
*
* @param beforeNotify a callback to run before sending errors to Bugsnag
* @see BeforeNotify
*/
public void beforeNotify(BeforeNotify beforeNotify) {
config.beforeNotify(beforeNotify);
}
/**
* Add a "before breadcrumb" callback, to execute code before every
* breadcrumb captured by Bugsnag.
* <p>
* You can use this to modify breadcrumbs before they are stored by Bugsnag.
* You can also return <code>false</code> from any callback to ignore a breadcrumb.
* <p>
* For example:
* <p>
* Bugsnag.beforeRecordBreadcrumb(new BeforeRecordBreadcrumb() {
* public boolean shouldRecord(Breadcrumb breadcrumb) {
* return false; // ignore the breadcrumb
* }
* })
*
* @param beforeRecordBreadcrumb a callback to run before a breadcrumb is captured
* @see BeforeRecordBreadcrumb
*/
public void beforeRecordBreadcrumb(BeforeRecordBreadcrumb beforeRecordBreadcrumb) {
config.beforeRecordBreadcrumb(beforeRecordBreadcrumb);
}
/**
* Notify Bugsnag of a handled exception
*
* @param exception the exception to send to Bugsnag
*/
public void notify(@NonNull Throwable exception) {
Error error = new Error.Builder(config, exception, sessionTracker.getCurrentSession())
.severityReasonType(HandledState.REASON_HANDLED_EXCEPTION)
.build();
notify(error, !BLOCKING);
}
/**
* Notify Bugsnag of a handled exception
*
* @param exception the exception to send to Bugsnag
* @param callback callback invoked on the generated error report for
* additional modification
*/
public void notify(@NonNull Throwable exception, Callback callback) {
Error error = new Error.Builder(config, exception, sessionTracker.getCurrentSession())
.severityReasonType(HandledState.REASON_HANDLED_EXCEPTION)
.build();
notify(error, DeliveryStyle.ASYNC, callback);
}
/**
* Notify Bugsnag of an error
*
* @param name the error name or class
* @param message the error message
* @param stacktrace the stackframes associated with the error
* @param callback callback invoked on the generated error report for
* additional modification
*/
public void notify(@NonNull String name,
@NonNull String message,
@NonNull StackTraceElement[] stacktrace,
Callback callback) {
Error error = new Error.Builder(config, name, message, stacktrace,
sessionTracker.getCurrentSession())
.severityReasonType(HandledState.REASON_HANDLED_EXCEPTION)
.build();
notify(error, DeliveryStyle.ASYNC, callback);
}
/**
* Notify Bugsnag of a handled exception
*
* @param exception the exception to send to Bugsnag
* @param severity the severity of the error, one of Severity.ERROR,
* Severity.WARNING or Severity.INFO
*/
public void notify(@NonNull Throwable exception, Severity severity) {
Error error = new Error.Builder(config, exception, sessionTracker.getCurrentSession())
.severity(severity)
.build();
notify(error, !BLOCKING);
}
/**
* Notify Bugsnag of a handled exception
*
* @param exception the exception to send to Bugsnag
* @param metaData additional information to send with the exception
* @deprecated Use {@link #notify(Throwable, Callback)} to send and modify error reports
*/
@Deprecated
public void notify(@NonNull Throwable exception,
@NonNull MetaData metaData) {
Error error = new Error.Builder(config, exception, sessionTracker.getCurrentSession())
.metaData(metaData)
.severityReasonType(HandledState.REASON_HANDLED_EXCEPTION)
.build();
notify(error, !BLOCKING);
}
/**
* Notify Bugsnag of a handled exception
*
* @param exception the exception to send to Bugsnag
* @param severity the severity of the error, one of Severity.ERROR,
* Severity.WARNING or Severity.INFO
* @param metaData additional information to send with the exception
* @deprecated Use {@link #notify(Throwable, Callback)} to send and modify error reports
*/
@Deprecated
public void notify(@NonNull Throwable exception, Severity severity,
@NonNull MetaData metaData) {
Error error = new Error.Builder(config, exception, sessionTracker.getCurrentSession())
.metaData(metaData)
.severity(severity)
.build();
notify(error, !BLOCKING);
}
/**
* Notify Bugsnag of an error
*
* @param name the error name or class
* @param message the error message
* @param stacktrace the stackframes associated with the error
* @param severity the severity of the error, one of Severity.ERROR,
* Severity.WARNING or Severity.INFO
* @param metaData additional information to send with the exception
* @deprecated Use {@link #notify(String, String, StackTraceElement[], Callback)}
* to send and modify error reports
*/
@Deprecated
public void notify(@NonNull String name, @NonNull String message,
@NonNull StackTraceElement[] stacktrace, Severity severity,
@NonNull MetaData metaData) {
Error error = new Error.Builder(config, name, message,
stacktrace, sessionTracker.getCurrentSession())
.severity(severity)
.metaData(metaData)
.build();
notify(error, !BLOCKING);
}
/**
* Notify Bugsnag of an error
*
* @param name the error name or class
* @param message the error message
* @param context the error context
* @param stacktrace the stackframes associated with the error
* @param severity the severity of the error, one of Severity.ERROR,
* Severity.WARNING or Severity.INFO
* @param metaData additional information to send with the exception
* @deprecated Use {@link #notify(String, String, StackTraceElement[], Callback)}
* to send and modify error reports
*/
@Deprecated
public void notify(@NonNull String name,
@NonNull String message,
String context,
@NonNull StackTraceElement[] stacktrace,
Severity severity,
@NonNull MetaData metaData) {
Error error = new Error.Builder(config, name, message,
stacktrace, sessionTracker.getCurrentSession())
.severity(severity)
.metaData(metaData)
.build();
error.setContext(context);
notify(error, !BLOCKING);
}
private void notify(@NonNull Error error, boolean blocking) {
DeliveryStyle style = blocking ? DeliveryStyle.SAME_THREAD : DeliveryStyle.ASYNC;
notify(error, style, null);
}
void notify(@NonNull Error error,
@NonNull DeliveryStyle style,
@Nullable Callback callback) {
// Don't notify if this error class should be ignored
if (error.shouldIgnoreClass()) {
return;
}
// generate new object each time, as this can be mutated by end-users
Map<String, Object> errorAppData = appData.getAppData();
// Don't notify unless releaseStage is in notifyReleaseStages
String releaseStage = getStringFromMap("releaseStage", errorAppData);
if (!config.shouldNotifyForReleaseStage(releaseStage)) {
return;
}
// Capture the state of the app and device and attach diagnostics to the error
Map<String, Object> errorDeviceData = deviceData.getDeviceData();
error.setDeviceData(errorDeviceData);
error.getMetaData().store.put("device", deviceData.getDeviceMetaData());
// add additional info that belongs in metadata
error.setAppData(errorAppData);
error.getMetaData().store.put("app", appData.getAppDataMetaData());
// Attach breadcrumbs to the error
error.setBreadcrumbs(breadcrumbs);
// Attach user info to the error
error.setUser(user);
// Run beforeNotify tasks, don't notify if any return true
if (!runBeforeNotifyTasks(error)) {
Logger.info("Skipping notification - beforeNotify task returned false");
return;
}
// Build the report
Report report = new Report(config.getApiKey(), error);
if (callback != null) {
callback.beforeNotify(report);
}
HandledState handledState = report.getError().getHandledState();
if (handledState.isUnhandled()) {
sessionTracker.incrementUnhandledError();
} else {
sessionTracker.incrementHandledError();
}
switch (style) {
case SAME_THREAD:
deliver(report, error);
break;
case ASYNC:
final Report finalReport = report;
final Error finalError = error;
// Attempt to send the report in the background
try {
Async.run(new Runnable() {
@Override
public void run() {
deliver(finalReport, finalError);
}
});
} catch (RejectedExecutionException exception) {
errorStore.write(error);
Logger.warn("Exceeded max queue count, saving to disk to send later");
}
break;
case ASYNC_WITH_CACHE:
errorStore.write(error);
errorStore.flushAsync();
break;
default:
break;
}
// Add a breadcrumb for this error occurring
String exceptionMessage = error.getExceptionMessage();
Map<String, String> message = Collections.singletonMap("message", exceptionMessage);
breadcrumbs.add(new Breadcrumb(error.getExceptionName(), BreadcrumbType.ERROR, message));
}
/**
* Notify Bugsnag of a handled exception
*
* @param exception the exception to send to Bugsnag
*/
public void notifyBlocking(@NonNull Throwable exception) {
Error error = new Error.Builder(config, exception, sessionTracker.getCurrentSession())
.severityReasonType(HandledState.REASON_HANDLED_EXCEPTION)
.build();
notify(error, BLOCKING);
}
/**
* Notify Bugsnag of a handled exception
*
* @param exception the exception to send to Bugsnag
* @param callback callback invoked on the generated error report for
* additional modification
*/
public void notifyBlocking(@NonNull Throwable exception, Callback callback) {
Error error = new Error.Builder(config, exception, sessionTracker.getCurrentSession())
.severityReasonType(HandledState.REASON_HANDLED_EXCEPTION)
.build();
notify(error, DeliveryStyle.SAME_THREAD, callback);
}
/**
* Notify Bugsnag of an error
*
* @param name the error name or class
* @param message the error message
* @param stacktrace the stackframes associated with the error
* @param callback callback invoked on the generated error report for
* additional modification
*/
public void notifyBlocking(@NonNull String name,
@NonNull String message,
@NonNull StackTraceElement[] stacktrace,
Callback callback) {
Error error = new Error.Builder(config, name, message,
stacktrace, sessionTracker.getCurrentSession())
.severityReasonType(HandledState.REASON_HANDLED_EXCEPTION)
.build();
notify(error, DeliveryStyle.SAME_THREAD, callback);
}
/**
* Notify Bugsnag of a handled exception
*
* @param exception the exception to send to Bugsnag
* @param metaData additional information to send with the exception
* @deprecated Use {@link #notify(Throwable, Callback)} to send and modify error reports
*/
@Deprecated
public void notifyBlocking(@NonNull Throwable exception,
@NonNull MetaData metaData) {
Error error = new Error.Builder(config, exception, sessionTracker.getCurrentSession())
.severityReasonType(HandledState.REASON_HANDLED_EXCEPTION)
.metaData(metaData)
.build();
notify(error, BLOCKING);
}
/**
* Notify Bugsnag of a handled exception
*
* @param exception the exception to send to Bugsnag
* @param severity the severity of the error, one of Severity.ERROR,
* Severity.WARNING or Severity.INFO
* @param metaData additional information to send with the exception
* @deprecated Use {@link #notifyBlocking(Throwable, Callback)} to send and modify error reports
*/
@Deprecated
public void notifyBlocking(@NonNull Throwable exception, Severity severity,
@NonNull MetaData metaData) {
Error error = new Error.Builder(config, exception, sessionTracker.getCurrentSession())
.metaData(metaData)
.severity(severity)
.build();
notify(error, BLOCKING);
}
/**
* Notify Bugsnag of an error
*
* @param name the error name or class
* @param message the error message
* @param stacktrace the stackframes associated with the error
* @param severity the severity of the error, one of Severity.ERROR,
* Severity.WARNING or Severity.INFO
* @param metaData additional information to send with the exception
* @deprecated Use {@link #notifyBlocking(String, String, StackTraceElement[], Callback)}
* to send and modify error reports
*/
@Deprecated
public void notifyBlocking(@NonNull String name,
@NonNull String message,
@NonNull StackTraceElement[] stacktrace,
Severity severity,
@NonNull MetaData metaData) {
Error error = new Error.Builder(config, name, message,
stacktrace, sessionTracker.getCurrentSession())
.severity(severity)