unhandledRejection.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  2. /** @author Brian Cavalier */
  3. /** @author John Hann */
  4. (function(define) { 'use strict';
  5. define(function(require) {
  6. var setTimer = require('../env').setTimer;
  7. var format = require('../format');
  8. return function unhandledRejection(Promise) {
  9. var logError = noop;
  10. var logInfo = noop;
  11. var localConsole;
  12. if(typeof console !== 'undefined') {
  13. // Alias console to prevent things like uglify's drop_console option from
  14. // removing console.log/error. Unhandled rejections fall into the same
  15. // category as uncaught exceptions, and build tools shouldn't silence them.
  16. localConsole = console;
  17. logError = typeof localConsole.error !== 'undefined'
  18. ? function (e) { localConsole.error(e); }
  19. : function (e) { localConsole.log(e); };
  20. logInfo = typeof localConsole.info !== 'undefined'
  21. ? function (e) { localConsole.info(e); }
  22. : function (e) { localConsole.log(e); };
  23. }
  24. Promise.onPotentiallyUnhandledRejection = function(rejection) {
  25. enqueue(report, rejection);
  26. };
  27. Promise.onPotentiallyUnhandledRejectionHandled = function(rejection) {
  28. enqueue(unreport, rejection);
  29. };
  30. Promise.onFatalRejection = function(rejection) {
  31. enqueue(throwit, rejection.value);
  32. };
  33. var tasks = [];
  34. var reported = [];
  35. var running = null;
  36. function report(r) {
  37. if(!r.handled) {
  38. reported.push(r);
  39. logError('Potentially unhandled rejection [' + r.id + '] ' + format.formatError(r.value));
  40. }
  41. }
  42. function unreport(r) {
  43. var i = reported.indexOf(r);
  44. if(i >= 0) {
  45. reported.splice(i, 1);
  46. logInfo('Handled previous rejection [' + r.id + '] ' + format.formatObject(r.value));
  47. }
  48. }
  49. function enqueue(f, x) {
  50. tasks.push(f, x);
  51. if(running === null) {
  52. running = setTimer(flush, 0);
  53. }
  54. }
  55. function flush() {
  56. running = null;
  57. while(tasks.length > 0) {
  58. tasks.shift()(tasks.shift());
  59. }
  60. }
  61. return Promise;
  62. };
  63. function throwit(e) {
  64. throw e;
  65. }
  66. function noop() {}
  67. });
  68. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));