zone-error.js 17 KB

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