-
Notifications
You must be signed in to change notification settings - Fork 211
/
Copy pathnotifier.js
executable file
·1090 lines (907 loc) · 29.8 KB
/
notifier.js
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
/* globals __NOTIFIER_VERSION__ */
/* globals __DEFAULT_ENDPOINT__ */
/* globals __DEFAULT_SCRUB_FIELDS__ */
/* globals __DEFAULT_LOG_LEVEL__ */
/* globals __DEFAULT_REPORT_LEVEL__ */
/* globals __DEFAULT_UNCAUGHT_ERROR_LEVEL */
/* globals __DEFAULT_ITEMS_PER_MIN__ */
/* globals __DEFAULT_MAX_ITEMS__ */
/* globals DOMException */
var extend = require('extend');
var errorParser = require('./error_parser');
var Util = require('./util');
var xhr = require('./xhr');
var XHR = xhr.XHR;
var ConnectionError = xhr.ConnectionError;
var RollbarJSON = null;
function setupJSON(JSON) {
RollbarJSON = JSON;
xhr.setupJSON(JSON);
Util.setupJSON(JSON);
}
function _wrapNotifierFn(fn, ctx) {
return function() {
var self = ctx || this;
try {
return fn.apply(self, arguments);
} catch (e) {
Util.consoleError('[Rollbar]:', e);
}
};
}
var payloadProcessorTimeout;
function _notifyPayloadAvailable() {
if (!payloadProcessorTimeout) {
payloadProcessorTimeout = setTimeout(_deferredPayloadProcess, 1000);
}
}
// Updated by the build process to match package.json
Notifier.NOTIFIER_VERSION = __NOTIFIER_VERSION__;
Notifier.DEFAULT_ENDPOINT = __DEFAULT_ENDPOINT__;
Notifier.DEFAULT_SCRUB_FIELDS = __DEFAULT_SCRUB_FIELDS__;
Notifier.DEFAULT_LOG_LEVEL = __DEFAULT_LOG_LEVEL__;
Notifier.DEFAULT_REPORT_LEVEL = __DEFAULT_REPORT_LEVEL__;
Notifier.DEFAULT_UNCAUGHT_ERROR_LEVEL = __DEFAULT_UNCAUGHT_ERROR_LEVEL;
Notifier.DEFAULT_ITEMS_PER_MIN = __DEFAULT_ITEMS_PER_MIN__;
Notifier.DEFAULT_MAX_ITEMS = __DEFAULT_MAX_ITEMS__;
Notifier.LEVELS = {
debug: 0,
info: 1,
warning: 2,
error: 3,
critical: 4
};
Notifier.RETRY_DELAY = 1000 * 10;
// This is the global queue where all notifiers will put their
// payloads to be sent to Rollbar.
window._rollbarPayloadQueue = window._rollbarPayloadQueue || [];
// This contains global options for all Rollbar notifiers.
window._globalRollbarOptions = {
startTime: (new Date()).getTime(),
maxItems: Notifier.DEFAULT_MAX_ITEMS,
itemsPerMinute: Notifier.DEFAULT_ITEMS_PER_MIN
};
var _topLevelNotifier;
function topLevelNotifier() {
return _topLevelNotifier;
}
function Notifier(parentNotifier) {
// Save the first notifier so we can use it to send system messages like
// when the rate limit is reached.
_topLevelNotifier = _topLevelNotifier || this;
var endpoint = 'https://' + Notifier.DEFAULT_ENDPOINT;
this.options = {
enabled: true,
endpoint: endpoint,
environment: 'production',
scrubFields: extend([], Notifier.DEFAULT_SCRUB_FIELDS),
checkIgnore: null,
logLevel: Notifier.DEFAULT_LOG_LEVEL,
reportLevel: Notifier.DEFAULT_REPORT_LEVEL,
uncaughtErrorLevel: Notifier.DEFAULT_UNCAUGHT_ERROR_LEVEL,
payload: {}
};
this.lastError = null;
this.plugins = {};
this.parentNotifier = parentNotifier;
if (parentNotifier) {
// If the parent notifier has the shimId
// property it means that it's a Rollbar shim.
if (parentNotifier.hasOwnProperty('shimId')) {
// After we set this, the shim is just a proxy to this
// Notifier instance.
parentNotifier.notifier = this;
} else {
this.configure(parentNotifier.options);
}
}
}
var NotifierPrototype = Notifier.prototype;
/*
* Returns an Object with keys:
* {
* message: String,
* err: Error,
* custom: Object
* }
*/
NotifierPrototype._getLogArgs = function(args) {
var level = this.options.logLevel || Notifier.DEFAULT_LOG_LEVEL;
var message;
var err;
var custom;
var callback;
var argT;
var arg;
var extraArgs = [];
for (var i = 0; i < args.length; ++i) {
arg = args[i];
argT = Util.typeName(arg);
if (argT === 'string') {
if (message) {
extraArgs.push(arg);
} else {
message = arg;
}
} else if (argT === 'function') {
callback = _wrapNotifierFn(arg, this); // wrap the callback in a try/catch block
} else if (argT === 'date') {
extraArgs.push(arg);
} else if (argT === 'error' ||
arg instanceof Error ||
(typeof DOMException !== 'undefined' && arg instanceof DOMException)) {
if (err) {
extraArgs.push(arg);
} else {
err = arg;
}
} else if (argT === 'object' || argT === 'array') {
if (custom) {
extraArgs.push(arg);
} else {
custom = arg;
}
}
}
// Save any of the extra arguments passed into the log function
// into `extraArgs` so they they show up in the payload.
if (extraArgs.length) {
custom = custom || {};
custom.extraArgs = extraArgs;
}
// TODO(cory): somehow pass in timestamp too...
return {
level: level,
message: message,
err: err,
custom: custom,
callback: callback
};
};
NotifierPrototype._route = function(path) {
var endpoint = this.options.endpoint;
var endpointTrailingSlash = /\/$/.test(endpoint);
var pathBeginningSlash = /^\//.test(path);
if (endpointTrailingSlash && pathBeginningSlash) {
path = path.substring(1);
} else if (!endpointTrailingSlash && !pathBeginningSlash) {
path = '/' + path;
}
return endpoint + path;
};
/*
* Given a queue containing each call to the shim, call the
* corresponding method on this instance.
*
* shim queue contains:
*
* {shim: Rollbar, method: 'info', args: ['hello world', exc], ts: Date}
*/
NotifierPrototype._processShimQueue = function(shimQueue) {
var shim;
var obj;
var method;
var args;
var shimToNotifier = {};
var parentShim;
var parentNotifier;
var notifier;
// For each of the messages in the shimQueue we need to:
// 1. get/create the notifier for that shim
// 2. apply the message to the notifier
while ((obj = shimQueue.shift())) {
shim = obj.shim;
method = obj.method;
args = obj.args;
parentShim = shim.parentShim;
// Get the current notifier based on the shimId
notifier = shimToNotifier[shim.shimId];
if (!notifier) {
// If there is no notifier associated with the shimId
// Check to see if there's a parent shim
if (parentShim) {
// If there is a parent shim, get the parent notifier
// and create a new notifier for the current shim.
parentNotifier = shimToNotifier[parentShim.shimId];
// Create a new Notifier which will process all of the shim's
// messages
notifier = new Notifier(parentNotifier);
} else {
// If there is no parent, assume the shim is the top
// level shim and thus, should use this as the notifier.
notifier = this;
}
// Save off the shimId->notifier mapping
shimToNotifier[shim.shimId] = notifier;
}
if (notifier[method] && Util.isType(notifier[method], 'function')) {
notifier[method].apply(notifier, args);
}
}
};
/*
* Builds and returns an Object that will be enqueued onto the
* window._rollbarPayloadQueue array to be sent to Rollbar.
*/
NotifierPrototype._buildPayload = function(ts, level, message, stackInfo, custom) {
var accessToken = this.options.accessToken;
// NOTE(cory): DEPRECATED
// Pass in {payload: {environment: 'production'}} instead of just {environment: 'production'}
var environment = this.options.environment;
var notifierOptions = extend(true, {}, this.options.payload);
var uuid = Util.uuid4();
if (Notifier.LEVELS[level] === undefined) {
throw new Error('Invalid level');
}
if (!message && !stackInfo && !custom) {
throw new Error('No message, stack info or custom data');
}
var payloadData = {
environment: environment,
endpoint: this.options.endpoint,
uuid: uuid,
level: level,
platform: 'browser',
framework: 'browser-js',
language: 'javascript',
body: this._buildBody(message, stackInfo, custom),
request: {
url: window.location.href,
query_string: window.location.search,
user_ip: '$remote_ip'
},
client: {
runtime_ms: ts.getTime() - window._globalRollbarOptions.startTime,
timestamp: Math.round(ts.getTime() / 1000),
javascript: {
browser: window.navigator.userAgent,
language: window.navigator.language,
cookie_enabled: window.navigator.cookieEnabled,
screen: {
width: window.screen.width,
height: window.screen.height
},
plugins: this._getBrowserPlugins()
}
},
server: {},
notifier: {
name: 'rollbar-browser-js',
version: Notifier.NOTIFIER_VERSION
}
};
if (notifierOptions.body) {
delete notifierOptions.body;
}
// Overwrite the options from configure() with the payload
// data.
var payload = {
access_token: accessToken,
data: extend(true, payloadData, notifierOptions)
};
// Only scrub the data section since we never want to scrub "access_token"
// even if it's in the scrub fields
this._scrub(payload.data);
return payload;
};
NotifierPrototype._buildBody = function(message, stackInfo, custom) {
var body;
if (stackInfo) {
body = _buildPayloadBodyTrace(message, stackInfo, custom);
} else {
body = _buildPayloadBodyMessage(message, custom);
}
return body;
};
NotifierPrototype._getBrowserPlugins = function() {
if (!this._browserPlugins) {
var navPlugins = window.navigator.plugins || [];
var cur;
var numPlugins = navPlugins.length;
var plugins = [];
var i;
for (i = 0; i < numPlugins; ++i) {
cur = navPlugins[i];
plugins.push({name: cur.name, description: cur.description});
}
this._browserPlugins = plugins;
}
return this._browserPlugins;
};
/*
* Does an in-place modification of obj such that:
* 1. All keys that match the notifier's options.scrubFields
* list will be normalized into all '*'
* 2. Any query string params that match the same criteria will have
* their values normalized as well.
*/
NotifierPrototype._scrub = function(obj) {
var scrubFields = this.options.scrubFields;
var paramRes = this._getScrubFieldRegexs(scrubFields);
var queryRes = this._getScrubQueryParamRegexs(scrubFields);
function redactQueryParam(dummy0, paramPart, dummy1, dummy2, dummy3, valPart) {
return paramPart + Util.redact(valPart);
}
function paramScrubber(v) {
var i;
if (Util.isType(v, 'string')) {
for (i = 0; i < queryRes.length; ++i) {
v = v.replace(queryRes[i], redactQueryParam);
}
}
return v;
}
function valScrubber(k, v) {
var i;
for (i = 0; i < paramRes.length; ++i) {
if (paramRes[i].test(k)) {
v = Util.redact(v);
break;
}
}
return v;
}
function scrubber(k, v) {
var tmpV = valScrubber(k, v);
if (tmpV === v) {
return paramScrubber(tmpV);
} else {
return tmpV;
}
}
Util.traverse(obj, scrubber);
return obj;
};
NotifierPrototype._getScrubFieldRegexs = function(scrubFields) {
var ret = [];
var pat;
for (var i = 0; i < scrubFields.length; ++i) {
pat = '\\[?(%5[bB])?' + scrubFields[i] + '\\[?(%5[bB])?\\]?(%5[dD])?';
ret.push(new RegExp(pat, 'i'));
}
return ret;
};
NotifierPrototype._getScrubQueryParamRegexs = function(scrubFields) {
var ret = [];
var pat;
for (var i = 0; i < scrubFields.length; ++i) {
pat = '\\[?(%5[bB])?' + scrubFields[i] + '\\[?(%5[bB])?\\]?(%5[dD])?';
ret.push(new RegExp('(' + pat + '=)([^&\\n]+)', 'igm'));
}
return ret;
};
NotifierPrototype._urlIsWhitelisted = function(payload){
var whitelist, trace, frame, filename, frameLength, url, listLength, urlRegex;
var i, j;
try {
whitelist = this.options.hostWhiteList;
trace = payload && payload.data && payload.data.body && payload.data.body.trace;
if (!whitelist || whitelist.length === 0) { return true; }
if (!trace) { return true; }
listLength = whitelist.length;
frameLength = trace.frames.length;
for (i = 0; i < frameLength; i++) {
frame = trace.frames[i];
filename = frame.filename;
if (!Util.isType(filename, 'string')) {
return true;
}
for (j = 0; j < listLength; j++) {
url = whitelist[j];
urlRegex = new RegExp(url);
if (urlRegex.test(filename)){
return true;
}
}
}
} catch (e) {
this.configure({hostWhiteList: null});
Util.consoleError("[Rollbar]: Error while reading your configuration's hostWhiteList option. Removing custom hostWhiteList.", e);
return true;
}
return false;
};
NotifierPrototype._messageIsIgnored = function(payload){
var exceptionMessage, i, ignoredMessages, len, messageIsIgnored, rIgnoredMessage, trace, body, traceMessage, bodyMessage;
try {
messageIsIgnored = false;
ignoredMessages = this.options.ignoredMessages;
if (!ignoredMessages || ignoredMessages.length === 0) {
return false;
}
body = payload &&
payload.data &&
payload.data.body;
traceMessage = body &&
body.trace &&
body.trace.exception &&
body.trace.exception.message;
bodyMessage = body &&
body.message &&
body.message.body;
exceptionMessage = traceMessage || bodyMessage;
if (!exceptionMessage){
return false;
}
len = ignoredMessages.length;
for (i = 0; i < len; i++) {
rIgnoredMessage = new RegExp(ignoredMessages[i], 'gi');
messageIsIgnored = rIgnoredMessage.test(exceptionMessage);
if (messageIsIgnored) {
break;
}
}
}
catch(e) {
this.configure({ignoredMessages: null});
Util.consoleError("[Rollbar]: Error while reading your configuration's ignoredMessages option. Removing custom ignoredMessages.");
}
return messageIsIgnored;
};
NotifierPrototype._enqueuePayload = function(payload, isUncaught, callerArgs, callback) {
var payloadToSend = {
callback: callback,
accessToken: this.options.accessToken,
endpointUrl: this._route('item/'),
payload: payload
};
var ignoredCallback = function() {
if (callback) {
// If the item was ignored call the callback anyway
var msg = 'This item was not sent to Rollbar because it was ignored. ' +
'This can happen if a custom checkIgnore() function was used ' +
'or if the item\'s level was less than the notifier\' reportLevel. ' +
'See https://rollbar.com/docs/notifier/rollbar.js/configuration for more details.';
callback(null, {err: 0, result: {id: null, uuid: null, message: msg}});
}
};
// Internal checkIgnore will check the level against the minimum
// report level from this.options
if (this._internalCheckIgnore(isUncaught, callerArgs, payload)) {
ignoredCallback();
return;
}
// Users can set their own ignore criteria using this.options.checkIgnore()
try {
if (Util.isType(this.options.checkIgnore, 'function') &&
this.options.checkIgnore(isUncaught, callerArgs, payload)) {
ignoredCallback();
return;
}
} catch (e) {
// Disable the custom checkIgnore and report errors in the checkIgnore function
this.configure({checkIgnore: null});
Util.consoleError('[Rollbar]: Error while calling custom checkIgnore() function. Removing custom checkIgnore().', e);
}
if (!this._urlIsWhitelisted(payload)) {
return;
}
if (this._messageIsIgnored(payload)) {
return;
}
if (this.options.verbose) {
if (payload.data && payload.data.body && payload.data.body.trace) {
var trace = payload.data.body.trace;
var exceptionMessage = trace.exception.message;
Util.consoleError('[Rollbar]: ', exceptionMessage);
}
Util.consoleInfo('[Rollbar]: ', payloadToSend);
}
if (Util.isType(this.options.logFunction, 'function')) {
this.options.logFunction(payloadToSend);
}
try {
if (Util.isType(this.options.transform, 'function')) {
this.options.transform(payload);
}
} catch (e) {
this.configure({transform: null});
Util.consoleError('[Rollbar]: Error while calling custom transform() function. Removing custom transform().', e);
}
if (this.options.enabled) {
directlyEnqueuePayload(payloadToSend);
}
};
function directlyEnqueuePayload(payloadToSend) {
window._rollbarPayloadQueue.push(payloadToSend);
_notifyPayloadAvailable();
}
NotifierPrototype._internalCheckIgnore = function(isUncaught, callerArgs, payload) {
var level = callerArgs[0];
var levelVal = Notifier.LEVELS[level] || 0;
var reportLevel = Notifier.LEVELS[this.options.reportLevel] || 0;
if (levelVal < reportLevel) {
return true;
}
var plugins = this.options ? this.options.plugins : {};
if (plugins && plugins.jquery && plugins.jquery.ignoreAjaxErrors) {
try {
// The jQuery plugin adds in this key. Return true if it exists since
// we are ignoring ajax errors via the plugin config.
return !!(payload.data.body.message.extra.isAjax);
} catch (e) {
return false;
}
}
return false;
};
/*
* Logs stuff to Rollbar using the default
* logging level.
*
* Can be called with the following, (order doesn't matter but type does):
* - message: String
* - err: Error object, must have a .stack property or it will be
* treated as custom data
* - custom: Object containing custom data to be sent along with
* the item
* - callback: Function to call once the item is reported to Rollbar
* - isUncaught: True if this error originated from an uncaught exception handler
* - ignoreRateLimit: True if this item should be allowed despite rate limit checks
*
* Returns an object with (at least) the "uuid" property set.
*/
NotifierPrototype._log = function(level, message, err, custom, callback, isUncaught, ignoreRateLimit) {
var stackInfo = null;
if (err) {
try {
// If we've already calculated the stack trace for the error, use it.
// This can happen for wrapped errors that don't have a "stack" property.
stackInfo = err._savedStackTrace ? err._savedStackTrace : errorParser.parse(err);
// Don't report the same error more than once
if (err === this.lastError) {
return;
}
this.lastError = err;
} catch (e) {
Util.consoleError('[Rollbar]: Error while parsing the error object.', e);
// err is not something we can parse so let's just send it along as a string
message = err.message || err.description || message || String(err);
err = null;
}
}
var payload = this._buildPayload(new Date(), level, message, stackInfo, custom);
if (ignoreRateLimit) {
payload.ignoreRateLimit = true;
}
this._enqueuePayload(payload, isUncaught ? true : false, [level, message, err, custom], callback);
// We're generating the UUID client-side, may as well return it so it can be
// used even before the payload has been sent to Rollbar. #236
// I'm returning an object here, in case we eventually want to add other
// contextual information besides the uuid.
return {uuid: payload.data.uuid};
};
NotifierPrototype.log = _generateLogFn();
NotifierPrototype.debug = _generateLogFn('debug');
NotifierPrototype.info = _generateLogFn('info');
NotifierPrototype.warn = _generateLogFn('warning'); // for console.warn() compatibility
NotifierPrototype.warning = _generateLogFn('warning');
NotifierPrototype.error = _generateLogFn('error');
NotifierPrototype.critical = _generateLogFn('critical');
// Adapted from tracekit.js
NotifierPrototype.uncaughtError = _wrapNotifierFn(function(message, url, lineNo, colNo, err, context) {
context = context || null;
if (err && Util.isType(err, 'error')) {
this._log(this.options.uncaughtErrorLevel, message, err, context, null, true);
return;
}
// NOTE(cory): sometimes users will trigger an "error" event
// on the window object directly which will result in errMsg
// being an Object instead of a string.
//
if (url && Util.isType(url, 'error')) {
this._log(this.options.uncaughtErrorLevel, message, url, context, null, true);
return;
}
var location = {
'url': url || '',
'line': lineNo
};
location.func = errorParser.guessFunctionName(location.url, location.line);
location.context = errorParser.gatherContext(location.url, location.line);
var stack = {
'mode': 'onerror',
'message': err ? String(err) : (message || 'uncaught exception'),
'url': document.location.href,
'stack': [location],
'useragent': navigator.userAgent
};
var payload = this._buildPayload(new Date(), this.options.uncaughtErrorLevel,
message, stack, context);
this._enqueuePayload(payload, true, [this.options.uncaughtErrorLevel,
message, url, lineNo, colNo, err]);
});
NotifierPrototype.unhandledRejection = _wrapNotifierFn(function(reason, promise) {
var message;
// If the reason error was thrown within a wrap call, we'll extract the context given there.
// If users want to provide their Promise implementation with knowledge of the rollbar
// context they are created in, we'll search for that attribute, too.
var context;
if (reason) {
message = reason.message || String(reason);
context = reason._rollbarContext;
} else {
message = 'unhandled rejection was null or undefined!';
}
context = context || promise._rollbarContext || null;
if (reason && Util.isType(reason, 'error')) {
this._log(this.options.uncaughtErrorLevel, message, reason, context, null, true);
return;
}
var location = {
'url': '',
'line': 0
};
location.func = errorParser.guessFunctionName(location.url, location.line);
location.context = errorParser.gatherContext(location.url, location.line);
var stack = {
'mode': 'unhandledrejection',
'message': message,
'url': document.location.href,
'stack': [location],
'useragent': navigator.userAgent
};
var payload = this._buildPayload(new Date(), this.options.uncaughtErrorLevel,
message, stack, context);
this._enqueuePayload(payload, true, [this.options.uncaughtErrorLevel,
message, location.url, location.line, 0, reason, promise]);
});
NotifierPrototype.global = _wrapNotifierFn(function(options) {
options = options || {};
var knownOptions = {
startTime: options.startTime,
maxItems: options.maxItems,
itemsPerMinute: options.itemsPerMinute
};
extend(true, window._globalRollbarOptions, knownOptions);
if (options.maxItems !== undefined) {
rateLimitCounter = 0;
}
if (options.itemsPerMinute !== undefined) {
rateLimitPerMinCounter = 0;
}
});
NotifierPrototype.configure = _wrapNotifierFn(function(options, overwrite) {
// TODO(cory): only allow non-payload keys that we understand
// Make a copy of the options object for this notifier
var newOptionsCopy = extend(true, {}, options);
extend(!overwrite, this.options, newOptionsCopy);
this.global(newOptionsCopy);
});
/*
* Create a new Notifier instance which has the same options
* as the current notifier + options to override them.
*/
NotifierPrototype.scope = _wrapNotifierFn(function(payloadOptions) {
var scopedNotifier = new Notifier(this);
extend(true, scopedNotifier.options.payload, payloadOptions);
return scopedNotifier;
});
NotifierPrototype.wrap = function(f, context) {
try {
var ctxFn;
if (Util.isType(context, 'function')) {
ctxFn = context;
} else {
ctxFn = function() {
return context || {};
};
}
if (!Util.isType(f, 'function')) {
return f;
}
// If the given function is already a wrapped function, just
// return it instead of wrapping twice
if (f._isWrap) {
return f;
}
if (!f._wrapped) {
f._wrapped = function () {
try {
return f.apply(this, arguments);
} catch(e) {
if (typeof e === 'string') {
e = new String(e);
}
if (!e.stack) {
e._savedStackTrace = errorParser.parse(e);
}
e._rollbarContext = ctxFn() || {};
e._rollbarContext._wrappedSource = f.toString();
window._rollbarWrappedError = e;
throw e;
}
};
f._wrapped._isWrap = true;
for (var prop in f) {
if (f.hasOwnProperty(prop)) {
f._wrapped[prop] = f[prop];
}
}
}
return f._wrapped;
} catch (e) {
// Try-catch here is to work around issue where wrap() fails when used inside Selenium.
// Return the original function if the wrap fails.
return f;
}
};
NotifierPrototype.loadFull = function() {
Util.consoleError('[Rollbar]: Unexpected Rollbar.loadFull() called on a Notifier instance');
};
/***** Misc *****/
function _generateLogFn(level) {
return _wrapNotifierFn(function _logFn() {
var args = this._getLogArgs(arguments);
return this._log(level || args.level || this.options.logLevel || Notifier.DEFAULT_LOG_LEVEL,
args.message, args.err, args.custom, args.callback);
});
}
function _buildPayloadBodyMessage(message, custom) {
if (!message) {
if (custom) {
message = RollbarJSON.stringify(custom);
} else {
message = '';
}
}
var result = {
body: message
};
if (custom) {
result.extra = extend(true, {}, custom);
}
return {
message: result
};
}
function _buildPayloadBodyTrace(description, stackInfo, custom) {
var guess = errorParser.guessErrorClass(stackInfo.message);
var className = stackInfo.name || guess[0];
var message = guess[1];
var trace = {
exception: {
'class': className,
message: message
}
};
if (description) {
trace.exception.description = description || 'uncaught exception';
}
// Transform a TraceKit stackInfo object into a Rollbar trace
if (stackInfo.stack) {
var stackFrame;
var frame;
var code;
var pre;
var post;
var contextLength;
var i, mid;
trace.frames = [];
for (i = 0; i < stackInfo.stack.length; ++i) {
stackFrame = stackInfo.stack[i];
frame = {
filename: stackFrame.url ? Util.sanitizeUrl(stackFrame.url) : '(unknown)',
lineno: stackFrame.line || null,
method: (!stackFrame.func || stackFrame.func === '?') ? '[anonymous]' : stackFrame.func,
colno: stackFrame.column
};
code = pre = post = null;
contextLength = stackFrame.context ? stackFrame.context.length : 0;
if (contextLength) {
mid = Math.floor(contextLength / 2);
pre = stackFrame.context.slice(0, mid);
code = stackFrame.context[mid];
post = stackFrame.context.slice(mid);
}
if (code) {
frame.code = code;
}
if (pre || post) {
frame.context = {};
if (pre && pre.length) {
frame.context.pre = pre;
}
if (post && post.length) {
frame.context.post = post;
}
}
if (stackFrame.args) {
frame.args = stackFrame.args;
}
trace.frames.push(frame);
}
// NOTE(cory): reverse the frames since rollbar.com expects the most recent call last
trace.frames.reverse();
if (custom) {
trace.extra = extend(true, {}, custom);
}
return {trace: trace};
} else {
// no frames - not useful as a trace. just report as a message.
return _buildPayloadBodyMessage(className + ': ' + message, custom);
}
}
/***** Payload processor *****/
Notifier.processPayloads = function(immediate) {
if (immediate) {
_deferredPayloadProcess();
return;
}
_notifyPayloadAvailable();
};