zone-error.js 15 KB

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