@samitouri / QOS-React-1 / commits / 3b2e5f27c5

[Fiber] Override the getCurrentStack temporarily while printing errors (#30300)

Only for parent stacks. This ensures that we can use the regular mechanism for appending stack traces. E.g. you can polyfill it. This is mainly so that I can later remove the automatic appending.

Sebastian Markbåge committed Jul 10, 2024 at 00:15 UTC 3b2e5f27c5b72708677da27779852b9aa83ef909
1 file changed +17 -16
packages/react-reconciler/src/ReactFiberErrorLogger.js
+17 -16
@@ -95,7 +95,19 @@ export function defaultOnCaughtError(
95 errorBoundaryName || 'Anonymous'
96 }.`;
97
98 - if (enableOwnerStacks) {
98 + const prevGetCurrentStack = ReactSharedInternals.getCurrentStack;
99 + if (!enableOwnerStacks) {
100 + // The current Fiber is disconnected at this point which means that console printing
101 + // cannot add a component stack since it terminates at the deletion node. This is not
102 + // a problem for owner stacks which are not disconnected but for the parent component
103 + // stacks we need to use the snapshot we've previously extracted.
104 + const componentStack =
105 + errorInfo.componentStack != null ? errorInfo.componentStack : '';
106 + ReactSharedInternals.getCurrentStack = function () {
107 + return componentStack;
108 + };
109 + }
110 + try {
111 if (
112 typeof error === 'object' &&
113 error !== null &&
@@ -123,21 +135,10 @@ export function defaultOnCaughtError(
135 // We let our consoleWithStackDev wrapper add the component stack to the end.
136 );
137 }
126 - } else {
127 - // The current Fiber is disconnected at this point which means that console printing
128 - // cannot add a component stack since it terminates at the deletion node. This is not
129 - // a problem for owner stacks which are not disconnected but for the parent component
130 - // stacks we need to use the snapshot we've previously extracted.
131 - const componentStack =
132 - errorInfo.componentStack != null ? errorInfo.componentStack : '';
133 - // Don't transform to our wrapper
134 - console['error'](
135 - '%o\n\n%s\n\n%s\n%s',
136 - error,
137 - componentNameMessage,
138 - recreateMessage,
139 - componentStack,
140 - );
138 + } finally {
139 + if (!enableOwnerStacks) {
140 + ReactSharedInternals.getCurrentStack = prevGetCurrentStack;
141 + }
142 }
143 } else {
144 // In production, we print the error directly.