zone-error.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. /**
  2. * @license
  3. * Copyright Google Inc. All Rights Reserved.
  4. *
  5. * Use of this source code is governed by an MIT-style license that can be
  6. * found in the LICENSE file at https://angular.io/license
  7. */
  8. (function (global, factory) {
  9. typeof exports === 'object' && typeof module !== 'undefined' ? factory() :
  10. typeof define === 'function' && define.amd ? define(factory) :
  11. (factory());
  12. }(this, (function () { 'use strict';
  13. /**
  14. * @license
  15. * Copyright Google Inc. All Rights Reserved.
  16. *
  17. * Use of this source code is governed by an MIT-style license that can be
  18. * found in the LICENSE file at https://angular.io/license
  19. */
  20. /**
  21. * @fileoverview
  22. * @suppress {globalThis,undefinedVars}
  23. */
  24. Zone.__load_patch('Error', function (global, Zone, api) {
  25. /*
  26. * This code patches Error so that:
  27. * - It ignores un-needed stack frames.
  28. * - It Shows the associated Zone for reach frame.
  29. */
  30. var blacklistedStackFramesSymbol = api.symbol('blacklistedStackFrames');
  31. var NativeError = global[api.symbol('Error')] = global['Error'];
  32. // Store the frames which should be removed from the stack frames
  33. var blackListedStackFrames = {};
  34. // We must find the frame where Error was created, otherwise we assume we don't understand stack
  35. var zoneAwareFrame1;
  36. var zoneAwareFrame2;
  37. var zoneAwareFrame1WithoutNew;
  38. var zoneAwareFrame2WithoutNew;
  39. var zoneAwareFrame3WithoutNew;
  40. global['Error'] = ZoneAwareError;
  41. var stackRewrite = 'stackRewrite';
  42. var blackListedStackFramesPolicy = global['__Zone_Error_BlacklistedStackFrames_policy'] || 'default';
  43. function buildZoneFrameNames(zoneFrame) {
  44. var zoneFrameName = { zoneName: zoneFrame.zone.name };
  45. var result = zoneFrameName;
  46. while (zoneFrame.parent) {
  47. zoneFrame = zoneFrame.parent;
  48. var parentZoneFrameName = { zoneName: zoneFrame.zone.name };
  49. zoneFrameName.parent = parentZoneFrameName;
  50. zoneFrameName = parentZoneFrameName;
  51. }
  52. return result;
  53. }
  54. function buildZoneAwareStackFrames(originalStack, zoneFrame, isZoneFrame) {
  55. if (isZoneFrame === void 0) { isZoneFrame = true; }
  56. var frames = originalStack.split('\n');
  57. var i = 0;
  58. // Find the first frame
  59. while (!(frames[i] === zoneAwareFrame1 || frames[i] === zoneAwareFrame2 ||
  60. frames[i] === zoneAwareFrame1WithoutNew || frames[i] === zoneAwareFrame2WithoutNew ||
  61. frames[i] === zoneAwareFrame3WithoutNew) &&
  62. i < frames.length) {
  63. i++;
  64. }
  65. for (; i < frames.length && zoneFrame; i++) {
  66. var frame = frames[i];
  67. if (frame.trim()) {
  68. switch (blackListedStackFrames[frame]) {
  69. case 0 /* blackList */:
  70. frames.splice(i, 1);
  71. i--;
  72. break;
  73. case 1 /* transition */:
  74. if (zoneFrame.parent) {
  75. // This is the special frame where zone changed. Print and process it accordingly
  76. zoneFrame = zoneFrame.parent;
  77. }
  78. else {
  79. zoneFrame = null;
  80. }
  81. frames.splice(i, 1);
  82. i--;
  83. break;
  84. default:
  85. frames[i] += isZoneFrame ? " [" + zoneFrame.zone.name + "]" :
  86. " [" + zoneFrame.zoneName + "]";
  87. }
  88. }
  89. }
  90. return frames.join('\n');
  91. }
  92. /**
  93. * This is ZoneAwareError which processes the stack frame and cleans up extra frames as well as
  94. * adds zone information to it.
  95. */
  96. function ZoneAwareError() {
  97. var _this = this;
  98. // We always have to return native error otherwise the browser console will not work.
  99. var error = NativeError.apply(this, arguments);
  100. // Save original stack trace
  101. var originalStack = error['originalStack'] = error.stack;
  102. // Process the stack trace and rewrite the frames.
  103. if (ZoneAwareError[stackRewrite] && originalStack) {
  104. var zoneFrame = api.currentZoneFrame();
  105. if (blackListedStackFramesPolicy === 'lazy') {
  106. // don't handle stack trace now
  107. error[api.symbol('zoneFrameNames')] = buildZoneFrameNames(zoneFrame);
  108. }
  109. else if (blackListedStackFramesPolicy === 'default') {
  110. try {
  111. error.stack = error.zoneAwareStack = buildZoneAwareStackFrames(originalStack, zoneFrame);
  112. }
  113. catch (e) {
  114. // ignore as some browsers don't allow overriding of stack
  115. }
  116. }
  117. }
  118. if (this instanceof NativeError && this.constructor != NativeError) {
  119. // We got called with a `new` operator AND we are subclass of ZoneAwareError
  120. // in that case we have to copy all of our properties to `this`.
  121. Object.keys(error).concat('stack', 'message').forEach(function (key) {
  122. var value = error[key];
  123. if (value !== undefined) {
  124. try {
  125. _this[key] = value;
  126. }
  127. catch (e) {
  128. // ignore the assignment in case it is a setter and it throws.
  129. }
  130. }
  131. });
  132. return this;
  133. }
  134. return error;
  135. }
  136. // Copy the prototype so that instanceof operator works as expected
  137. ZoneAwareError.prototype = NativeError.prototype;
  138. ZoneAwareError[blacklistedStackFramesSymbol] = blackListedStackFrames;
  139. ZoneAwareError[stackRewrite] = false;
  140. var zoneAwareStackSymbol = api.symbol('zoneAwareStack');
  141. // try to define zoneAwareStack property when blackListed
  142. // policy is delay
  143. if (blackListedStackFramesPolicy === 'lazy') {
  144. Object.defineProperty(ZoneAwareError.prototype, 'zoneAwareStack', {
  145. configurable: true,
  146. enumerable: true,
  147. get: function () {
  148. if (!this[zoneAwareStackSymbol]) {
  149. this[zoneAwareStackSymbol] = buildZoneAwareStackFrames(this.originalStack, this[api.symbol('zoneFrameNames')], false);
  150. }
  151. return this[zoneAwareStackSymbol];
  152. },
  153. set: function (newStack) {
  154. this.originalStack = newStack;
  155. this[zoneAwareStackSymbol] = buildZoneAwareStackFrames(this.originalStack, this[api.symbol('zoneFrameNames')], false);
  156. }
  157. });
  158. }
  159. // those properties need special handling
  160. var specialPropertyNames = ['stackTraceLimit', 'captureStackTrace', 'prepareStackTrace'];
  161. // those properties of NativeError should be set to ZoneAwareError
  162. var nativeErrorProperties = Object.keys(NativeError);
  163. if (nativeErrorProperties) {
  164. nativeErrorProperties.forEach(function (prop) {
  165. if (specialPropertyNames.filter(function (sp) { return sp === prop; }).length === 0) {
  166. Object.defineProperty(ZoneAwareError, prop, {
  167. get: function () {
  168. return NativeError[prop];
  169. },
  170. set: function (value) {
  171. NativeError[prop] = value;
  172. }
  173. });
  174. }
  175. });
  176. }
  177. if (NativeError.hasOwnProperty('stackTraceLimit')) {
  178. // Extend default stack limit as we will be removing few frames.
  179. NativeError.stackTraceLimit = Math.max(NativeError.stackTraceLimit, 15);
  180. // make sure that ZoneAwareError has the same property which forwards to NativeError.
  181. Object.defineProperty(ZoneAwareError, 'stackTraceLimit', {
  182. get: function () {
  183. return NativeError.stackTraceLimit;
  184. },
  185. set: function (value) {
  186. return NativeError.stackTraceLimit = value;
  187. }
  188. });
  189. }
  190. if (NativeError.hasOwnProperty('captureStackTrace')) {
  191. Object.defineProperty(ZoneAwareError, 'captureStackTrace', {
  192. // add named function here because we need to remove this
  193. // stack frame when prepareStackTrace below
  194. value: function zoneCaptureStackTrace(targetObject, constructorOpt) {
  195. NativeError.captureStackTrace(targetObject, constructorOpt);
  196. }
  197. });
  198. }
  199. var ZONE_CAPTURESTACKTRACE = 'zoneCaptureStackTrace';
  200. Object.defineProperty(ZoneAwareError, 'prepareStackTrace', {
  201. get: function () {
  202. return NativeError.prepareStackTrace;
  203. },
  204. set: function (value) {
  205. if (!value || typeof value !== 'function') {
  206. return NativeError.prepareStackTrace = value;
  207. }
  208. return NativeError.prepareStackTrace = function (error, structuredStackTrace) {
  209. // remove additional stack information from ZoneAwareError.captureStackTrace
  210. if (structuredStackTrace) {
  211. for (var i = 0; i < structuredStackTrace.length; i++) {
  212. var st = structuredStackTrace[i];
  213. // remove the first function which name is zoneCaptureStackTrace
  214. if (st.getFunctionName() === ZONE_CAPTURESTACKTRACE) {
  215. structuredStackTrace.splice(i, 1);
  216. break;
  217. }
  218. }
  219. }
  220. return value.call(this, error, structuredStackTrace);
  221. };
  222. }
  223. });
  224. if (blackListedStackFramesPolicy === 'disable') {
  225. // don't need to run detectZone to populate
  226. // blacklisted stack frames
  227. return;
  228. }
  229. // Now we need to populate the `blacklistedStackFrames` as well as find the
  230. // run/runGuarded/runTask frames. This is done by creating a detect zone and then threading
  231. // the execution through all of the above methods so that we can look at the stack trace and
  232. // find the frames of interest.
  233. var detectZone = Zone.current.fork({
  234. name: 'detect',
  235. onHandleError: function (parentZD, current, target, error) {
  236. if (error.originalStack && Error === ZoneAwareError) {
  237. var frames_1 = error.originalStack.split(/\n/);
  238. var runFrame = false, runGuardedFrame = false, runTaskFrame = false;
  239. while (frames_1.length) {
  240. var frame = frames_1.shift();
  241. // On safari it is possible to have stack frame with no line number.
  242. // This check makes sure that we don't filter frames on name only (must have
  243. // line number or exact equals to `ZoneAwareError`)
  244. if (/:\d+:\d+/.test(frame) || frame === 'ZoneAwareError') {
  245. // Get rid of the path so that we don't accidentally find function name in path.
  246. // In chrome the separator is `(` and `@` in FF and safari
  247. // Chrome: at Zone.run (zone.js:100)
  248. // Chrome: at Zone.run (http://localhost:9876/base/build/lib/zone.js:100:24)
  249. // FireFox: Zone.prototype.run@http://localhost:9876/base/build/lib/zone.js:101:24
  250. // Safari: run@http://localhost:9876/base/build/lib/zone.js:101:24
  251. var fnName = frame.split('(')[0].split('@')[0];
  252. var frameType = 1;
  253. if (fnName.indexOf('ZoneAwareError') !== -1) {
  254. if (fnName.indexOf('new ZoneAwareError') !== -1) {
  255. zoneAwareFrame1 = frame;
  256. zoneAwareFrame2 = frame.replace('new ZoneAwareError', 'new Error.ZoneAwareError');
  257. }
  258. else {
  259. zoneAwareFrame1WithoutNew = frame;
  260. zoneAwareFrame2WithoutNew = frame.replace('Error.', '');
  261. if (frame.indexOf('Error.ZoneAwareError') === -1) {
  262. zoneAwareFrame3WithoutNew =
  263. frame.replace('ZoneAwareError', 'Error.ZoneAwareError');
  264. }
  265. }
  266. blackListedStackFrames[zoneAwareFrame2] = 0 /* blackList */;
  267. }
  268. if (fnName.indexOf('runGuarded') !== -1) {
  269. runGuardedFrame = true;
  270. }
  271. else if (fnName.indexOf('runTask') !== -1) {
  272. runTaskFrame = true;
  273. }
  274. else if (fnName.indexOf('run') !== -1) {
  275. runFrame = true;
  276. }
  277. else {
  278. frameType = 0 /* blackList */;
  279. }
  280. blackListedStackFrames[frame] = frameType;
  281. // Once we find all of the frames we can stop looking.
  282. if (runFrame && runGuardedFrame && runTaskFrame) {
  283. ZoneAwareError[stackRewrite] = true;
  284. break;
  285. }
  286. }
  287. }
  288. }
  289. return false;
  290. }
  291. });
  292. // carefully constructor a stack frame which contains all of the frames of interest which
  293. // need to be detected and blacklisted.
  294. var childDetectZone = detectZone.fork({
  295. name: 'child',
  296. onScheduleTask: function (delegate, curr, target, task) {
  297. return delegate.scheduleTask(target, task);
  298. },
  299. onInvokeTask: function (delegate, curr, target, task, applyThis, applyArgs) {
  300. return delegate.invokeTask(target, task, applyThis, applyArgs);
  301. },
  302. onCancelTask: function (delegate, curr, target, task) {
  303. return delegate.cancelTask(target, task);
  304. },
  305. onInvoke: function (delegate, curr, target, callback, applyThis, applyArgs, source) {
  306. return delegate.invoke(target, callback, applyThis, applyArgs, source);
  307. }
  308. });
  309. // we need to detect all zone related frames, it will
  310. // exceed default stackTraceLimit, so we set it to
  311. // larger number here, and restore it after detect finish.
  312. var originalStackTraceLimit = Error.stackTraceLimit;
  313. Error.stackTraceLimit = 100;
  314. // we schedule event/micro/macro task, and invoke them
  315. // when onSchedule, so we can get all stack traces for
  316. // all kinds of tasks with one error thrown.
  317. childDetectZone.run(function () {
  318. childDetectZone.runGuarded(function () {
  319. var fakeTransitionTo = function () { };
  320. childDetectZone.scheduleEventTask(blacklistedStackFramesSymbol, function () {
  321. childDetectZone.scheduleMacroTask(blacklistedStackFramesSymbol, function () {
  322. childDetectZone.scheduleMicroTask(blacklistedStackFramesSymbol, function () {
  323. throw new Error();
  324. }, undefined, function (t) {
  325. t._transitionTo = fakeTransitionTo;
  326. t.invoke();
  327. });
  328. childDetectZone.scheduleMicroTask(blacklistedStackFramesSymbol, function () {
  329. throw Error();
  330. }, undefined, function (t) {
  331. t._transitionTo = fakeTransitionTo;
  332. t.invoke();
  333. });
  334. }, undefined, function (t) {
  335. t._transitionTo = fakeTransitionTo;
  336. t.invoke();
  337. }, function () { });
  338. }, undefined, function (t) {
  339. t._transitionTo = fakeTransitionTo;
  340. t.invoke();
  341. }, function () { });
  342. });
  343. });
  344. Error.stackTraceLimit = originalStackTraceLimit;
  345. });
  346. })));