Skip to content

Commit 6294c34

Browse files
committed
[Fiber] Don't Rethrow Errors at the Root (#28627)
Stacked on top of #28498 for test fixes. ### Don't Rethrow When we started React it was 1:1 setState calls a series of renders and if they error, it errors where the setState was called. Simple. However, then batching came and the error actually got thrown somewhere else. With concurrent mode, it's not even possible to get setState itself to throw anymore. In fact, all APIs that can rethrow out of React are executed either at the root of the scheduler or inside a DOM event handler. If you throw inside a React.startTransition callback that's sync, then that will bubble out of the startTransition but if you throw inside an async callback or a useTransition we now need to handle it at the hook site. So in 19 we need to make all React.startTransition swallow the error (and report them to reportError). The only one remaining that can throw is flushSync but it doesn't really make sense for it to throw at the callsite neither because batching. Just because something rendered in this flush doesn't mean it was rendered due to what was just scheduled and doesn't mean that it should abort any of the remaining code afterwards. setState is fire and forget. It's send an instruction elsewhere, it's not part of the current imperative code. Error boundaries never rethrow. Since you should really always have error boundaries, most of the time, it wouldn't rethrow anyway. Rethrowing also actually currently drops errors on the floor since we can only rethrow the first error, so to avoid that we'd need to call reportError anyway. This happens in RN events. The other issue with rethrowing is that it logs an extra console.error. Since we're not sure that user code will actually log it anywhere we still log it too just like we do with errors inside error boundaries which leads all of these to log twice. The goal of this PR is to never rethrow out of React instead, errors outside of error boundaries get logged to reportError. Event system errors too. ### Breaking Changes The main thing this affects is testing where you want to inspect the errors thrown. To make it easier to port, if you're inside `act` we track the error into act in an aggregate error and then rethrow it at the root of `act`. Unlike before though, if you flush synchronously inside of act it'll still continue until the end of act before rethrowing. I expect most user code breakages would be to migrate from `flushSync` to `act` if you assert on throwing. However, in the React repo we also have `internalAct` and the `waitForThrow` helpers. Since these have to use public production implementations we track these using the global onerror or process uncaughtException. Unlike regular act, includes both event handler errors and onRecoverableError by default too. Not just render/commit errors. So I had to account for that in our tests. We restore logging an extra log for uncaught errors after the main log with the component stack in it. We use `console.warn`. This is not yet ignorable if you preventDefault to the main error event. To avoid confusion if you don't end up logging the error to console I just added `An error occurred`. ### Polyfill All browsers we support really supports `reportError` but not all test and server environments do, so I implemented a polyfill for browser and node in `shared/reportGlobalError`. I don't love that this is included in all builds and gets duplicated into isomorphic even though it's not actually needed in production. Maybe in the future we can require a polyfill for this. ### Follow Ups In a follow up, I'll make caught vs uncaught error handling be configurable too. --------- Co-authored-by: Ricky Hanlon <[email protected]> DiffTrain build for [6786563](6786563)
1 parent b8ac8eb commit 6294c34

25 files changed

+4032
-3745
lines changed

compiled/facebook-www/REVISION

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
5910eb34567a8699d1faa73b546baafd94f26411
1+
6786563f3cbbc9b16d5a8187207b5bd904386e53

compiled/facebook-www/React-dev.classic.js

Lines changed: 102 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ if (__DEV__) {
2424
) {
2525
__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error());
2626
}
27-
var ReactVersion = "19.0.0-www-classic-5d26d7ce";
27+
var ReactVersion = "19.0.0-www-classic-8c9925ed";
2828

2929
// ATTENTION
3030
// When adding new symbols to this file,
@@ -644,7 +644,9 @@ if (__DEV__) {
644644
// Tracks whether something called `use` during the current batch of work.
645645
// Determines whether we should yield to microtasks to unwrap already resolved
646646
// promises without suspending.
647-
didUsePromise: false
647+
didUsePromise: false,
648+
// Track first uncaught error within this act
649+
thrownErrors: []
648650
};
649651

650652
/**
@@ -3164,6 +3166,45 @@ if (__DEV__) {
31643166
}
31653167
}
31663168

3169+
var reportGlobalError =
3170+
typeof reportError === "function" // In modern browsers, reportError will dispatch an error event,
3171+
? // emulating an uncaught JavaScript error.
3172+
reportError
3173+
: function (error) {
3174+
if (
3175+
typeof window === "object" &&
3176+
typeof window.ErrorEvent === "function"
3177+
) {
3178+
// Browser Polyfill
3179+
var message =
3180+
typeof error === "object" &&
3181+
error !== null &&
3182+
typeof error.message === "string" // eslint-disable-next-line react-internal/safe-string-coercion
3183+
? String(error.message) // eslint-disable-next-line react-internal/safe-string-coercion
3184+
: String(error);
3185+
var event = new window.ErrorEvent("error", {
3186+
bubbles: true,
3187+
cancelable: true,
3188+
message: message,
3189+
error: error
3190+
});
3191+
var shouldLog = window.dispatchEvent(event);
3192+
3193+
if (!shouldLog) {
3194+
return;
3195+
}
3196+
} else if (
3197+
typeof process === "object" && // $FlowFixMe[method-unbinding]
3198+
typeof process.emit === "function"
3199+
) {
3200+
// Node Polyfill
3201+
process.emit("uncaughtException", error);
3202+
return;
3203+
} // eslint-disable-next-line react-internal/no-production-logging
3204+
3205+
console["error"](error);
3206+
};
3207+
31673208
function startTransition(scope, options) {
31683209
var prevTransition = ReactCurrentBatchConfig.transition; // Each renderer registers a callback to receive the return value of
31693210
// the scope function. This is used to implement async actions.
@@ -3200,10 +3241,10 @@ if (__DEV__) {
32003241
callbacks.forEach(function (callback) {
32013242
return callback(currentTransition, returnValue);
32023243
});
3203-
returnValue.then(noop, onError);
3244+
returnValue.then(noop, reportGlobalError);
32043245
}
32053246
} catch (error) {
3206-
onError(error);
3247+
reportGlobalError(error);
32073248
} finally {
32083249
warnAboutTransitionSubscriptions(prevTransition, currentTransition);
32093250
ReactCurrentBatchConfig.transition = prevTransition;
@@ -3232,18 +3273,7 @@ if (__DEV__) {
32323273
}
32333274
}
32343275

3235-
function noop() {} // Use reportError, if it exists. Otherwise console.error. This is the same as
3236-
// the default for onRecoverableError.
3237-
3238-
var onError =
3239-
typeof reportError === "function" // In modern browsers, reportError will dispatch an error event,
3240-
? // emulating an uncaught JavaScript error.
3241-
reportError
3242-
: function (error) {
3243-
// In older browsers and test environments, fallback to console.error.
3244-
// eslint-disable-next-line react-internal/no-production-logging
3245-
console["error"](error);
3246-
};
3276+
function noop() {}
32473277

32483278
var didWarnAboutMessageChannel = false;
32493279
var enqueueTaskImpl = null;
@@ -3292,6 +3322,16 @@ if (__DEV__) {
32923322
var actScopeDepth = 0; // We only warn the first time you neglect to await an async `act` scope.
32933323

32943324
var didWarnNoAwaitAct = false;
3325+
3326+
function aggregateErrors(errors) {
3327+
if (errors.length > 1 && typeof AggregateError === "function") {
3328+
// eslint-disable-next-line no-undef
3329+
return new AggregateError(errors);
3330+
}
3331+
3332+
return errors[0];
3333+
}
3334+
32953335
function act(callback) {
32963336
{
32973337
// When ReactCurrentActQueue.current is not null, it signals to React that
@@ -3343,9 +3383,15 @@ if (__DEV__) {
33433383
// one used to track `act` scopes. Why, you may be wondering? Because
33443384
// that's how it worked before version 18. Yes, it's confusing! We should
33453385
// delete legacy mode!!
3386+
ReactCurrentActQueue.thrownErrors.push(error);
3387+
}
3388+
3389+
if (ReactCurrentActQueue.thrownErrors.length > 0) {
33463390
ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy;
33473391
popActScope(prevActQueue, prevActScopeDepth);
3348-
throw error;
3392+
var thrownError = aggregateErrors(ReactCurrentActQueue.thrownErrors);
3393+
ReactCurrentActQueue.thrownErrors.length = 0;
3394+
throw thrownError;
33493395
}
33503396

33513397
if (
@@ -3400,15 +3446,34 @@ if (__DEV__) {
34003446
// `thenable` might not be a real promise, and `flushActQueue`
34013447
// might throw, so we need to wrap `flushActQueue` in a
34023448
// try/catch.
3403-
reject(error);
3449+
ReactCurrentActQueue.thrownErrors.push(error);
3450+
}
3451+
3452+
if (ReactCurrentActQueue.thrownErrors.length > 0) {
3453+
var _thrownError = aggregateErrors(
3454+
ReactCurrentActQueue.thrownErrors
3455+
);
3456+
3457+
ReactCurrentActQueue.thrownErrors.length = 0;
3458+
reject(_thrownError);
34043459
}
34053460
} else {
34063461
resolve(returnValue);
34073462
}
34083463
},
34093464
function (error) {
34103465
popActScope(prevActQueue, prevActScopeDepth);
3411-
reject(error);
3466+
3467+
if (ReactCurrentActQueue.thrownErrors.length > 0) {
3468+
var _thrownError2 = aggregateErrors(
3469+
ReactCurrentActQueue.thrownErrors
3470+
);
3471+
3472+
ReactCurrentActQueue.thrownErrors.length = 0;
3473+
reject(_thrownError2);
3474+
} else {
3475+
reject(error);
3476+
}
34123477
}
34133478
);
34143479
}
@@ -3461,6 +3526,15 @@ if (__DEV__) {
34613526
ReactCurrentActQueue.current = null;
34623527
}
34633528

3529+
if (ReactCurrentActQueue.thrownErrors.length > 0) {
3530+
var _thrownError3 = aggregateErrors(
3531+
ReactCurrentActQueue.thrownErrors
3532+
);
3533+
3534+
ReactCurrentActQueue.thrownErrors.length = 0;
3535+
throw _thrownError3;
3536+
}
3537+
34643538
return {
34653539
then: function (resolve, reject) {
34663540
didAwaitActCall = true;
@@ -3517,15 +3591,21 @@ if (__DEV__) {
35173591
reject
35183592
);
35193593
});
3594+
return;
35203595
} catch (error) {
35213596
// Leave remaining tasks on the queue if something throws.
3522-
reject(error);
3597+
ReactCurrentActQueue.thrownErrors.push(error);
35233598
}
35243599
} else {
35253600
// The queue is empty. We can finish.
35263601
ReactCurrentActQueue.current = null;
3527-
resolve(returnValue);
35283602
}
3603+
}
3604+
3605+
if (ReactCurrentActQueue.thrownErrors.length > 0) {
3606+
var thrownError = aggregateErrors(ReactCurrentActQueue.thrownErrors);
3607+
ReactCurrentActQueue.thrownErrors.length = 0;
3608+
reject(thrownError);
35293609
} else {
35303610
resolve(returnValue);
35313611
}
@@ -3570,7 +3650,7 @@ if (__DEV__) {
35703650
} catch (error) {
35713651
// If something throws, leave the remaining callbacks on the queue.
35723652
queue.splice(0, i + 1);
3573-
throw error;
3653+
ReactCurrentActQueue.thrownErrors.push(error);
35743654
} finally {
35753655
isFlushing = false;
35763656
}

0 commit comments

Comments
 (0)