/
unhandledRejection.js
102 lines (82 loc) · 2.28 KB
/
unhandledRejection.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
/** @license MIT License (c) copyright 2010-2014 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
(function(define) { 'use strict';
define(function(require) {
var setTimer = require('../env').setTimer;
return function unhandledRejection(Promise) {
var logError = noop;
var logInfo = noop;
if(typeof console !== 'undefined') {
logError = typeof console.error !== 'undefined'
? function (e) { console.error(e); }
: function (e) { console.log(e); };
logInfo = typeof console.info !== 'undefined'
? function (e) { console.info(e); }
: function (e) { console.log(e); };
}
Promise.onPotentiallyUnhandledRejection = function(rejection) {
enqueue(report, rejection);
};
Promise.onPotentiallyUnhandledRejectionHandled = function(rejection) {
enqueue(unreport, rejection);
};
Promise.onFatalRejection = function(rejection) {
enqueue(throwit, rejection.value);
};
var tasks = [];
var reported = [];
var running = false;
function report(r) {
if(!r.handled) {
reported.push(r);
logError('Potentially unhandled rejection [' + r.id + '] ' + formatError(r.value));
}
}
function unreport(r) {
var i = reported.indexOf(r);
if(i >= 0) {
reported.splice(i, 1);
logInfo('Handled previous rejection [' + r.id + '] ' + formatObject(r.value));
}
}
function enqueue(f, x) {
tasks.push(f, x);
if(!running) {
running = true;
running = setTimer(flush, 0);
}
}
function flush() {
running = false;
while(tasks.length > 0) {
tasks.shift()(tasks.shift());
}
}
return Promise;
};
function formatError(e) {
var s = typeof e === 'object' && e.stack ? e.stack : formatObject(e);
return e instanceof Error ? s : s + ' (WARNING: non-Error used)';
}
function formatObject(o) {
var s = String(o);
if(s === '[object Object]' && typeof JSON !== 'undefined') {
s = tryStringify(o, s);
}
return s;
}
function tryStringify(e, defaultValue) {
try {
return JSON.stringify(e);
} catch(e) {
// Ignore. Cannot JSON.stringify e, stick with String(e)
return defaultValue;
}
}
function throwit(e) {
throw e;
}
function noop() {}
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));