Commit dbab205b authored by Zack Tanner's avatar Zack Tanner

ensure server action errors notify rejection handlers (#61588)

### What
When attaching a rejection listener to a server action promise, in the case of network errors, the rejection handler would be skipped and it'd throw an error that crashes the application.

### Why
When we refactored these reducers to no longer suspend, it caused the rejection handling logic we have to no longer make sense. In this case we're working with a native promise that won't have a `status` property, so we'd re-throw the error and not call `reject`. 

### How
This removes the special status handling logic and makes the rejection handler always call `reject` with the error. This will either be handled by user code or let the error bubble to an error boundary. 

I also cleaned up some mutable code that is no longer needed now that these reducers aren't replayed. 

Closes NEXT-1715
Closes NEXT-2323
Fixes #58638
parent a70ae409
...@@ -165,8 +165,6 @@ export function serverActionReducer( ...@@ -165,8 +165,6 @@ export function serverActionReducer(
mutable.preserveCustomHistoryState = false mutable.preserveCustomHistoryState = false
mutable.inFlightServerAction = fetchServerAction(state, action) mutable.inFlightServerAction = fetchServerAction(state, action)
// suspends until the server action is resolved.
return mutable.inFlightServerAction.then( return mutable.inFlightServerAction.then(
({ actionResult, actionFlightData: flightData, redirectLocation }) => { ({ actionResult, actionFlightData: flightData, redirectLocation }) => {
// Make sure the redirection is a push instead of a replace. // Make sure the redirection is a push instead of a replace.
...@@ -177,10 +175,7 @@ export function serverActionReducer( ...@@ -177,10 +175,7 @@ export function serverActionReducer(
} }
if (!flightData) { if (!flightData) {
if (!mutable.actionResultResolved) { resolve(actionResult)
resolve(actionResult)
mutable.actionResultResolved = true
}
// If there is a redirect but no flight data we need to do a mpaNavigation. // If there is a redirect but no flight data we need to do a mpaNavigation.
if (redirectLocation) { if (redirectLocation) {
...@@ -269,24 +264,15 @@ export function serverActionReducer( ...@@ -269,24 +264,15 @@ export function serverActionReducer(
mutable.canonicalUrl = newHref mutable.canonicalUrl = newHref
} }
if (!mutable.actionResultResolved) { resolve(actionResult)
resolve(actionResult)
mutable.actionResultResolved = true
}
return handleMutable(state, mutable) return handleMutable(state, mutable)
}, },
(e: any) => { (e: any) => {
if (e.status === 'rejected') { // When the server action is rejected we don't update the state and instead call the reject handler of the promise.
if (!mutable.actionResultResolved) { reject(e.reason)
reject(e.reason)
mutable.actionResultResolved = true
}
// When the server action is rejected we don't update the state and instead call the reject handler of the promise.
return state
}
throw e return state
} }
) )
} }
...@@ -41,7 +41,6 @@ export interface Mutable { ...@@ -41,7 +41,6 @@ export interface Mutable {
export interface ServerActionMutable extends Mutable { export interface ServerActionMutable extends Mutable {
inFlightServerAction?: Promise<any> | null inFlightServerAction?: Promise<any> | null
actionResultResolved?: boolean
} }
/** /**
......
/* eslint-disable jest/no-standalone-expect */ /* eslint-disable jest/no-standalone-expect */
import { createNextDescribe } from 'e2e-utils' import { createNextDescribe } from 'e2e-utils'
import { check, waitFor } from 'next-test-utils' import { check, waitFor } from 'next-test-utils'
import { Request, Response } from 'playwright-chromium' import { Request, Response, Route } from 'playwright-chromium'
import fs from 'fs-extra' import fs from 'fs-extra'
import { join } from 'path' import { join } from 'path'
...@@ -444,6 +444,51 @@ createNextDescribe( ...@@ -444,6 +444,51 @@ createNextDescribe(
) )
}) })
it('should be possible to catch network errors', async () => {
const browser = await next.browser('/catching-error', {
beforePageLoad(page) {
page.route('**/catching-error', (route: Route) => {
if (route.request().method() !== 'POST') {
route.fallback()
return
}
route.abort('internetdisconnected')
})
},
})
await browser.elementById('good-action').click()
// verify that the app didn't crash after the error was thrown
expect(await browser.elementById('submitted-msg').text()).toBe(
'Submitted!'
)
// Verify that the catch log was printed
const logs = await browser.log()
expect(
logs.some((log) => log.message === 'error caught in user code')
).toBe(true)
})
it('should be possible to catch regular errors', async () => {
const browser = await next.browser('/catching-error')
await browser.elementById('bad-action').click()
// verify that the app didn't crash after the error was thrown
expect(await browser.elementById('submitted-msg').text()).toBe(
'Submitted!'
)
// Verify that the catch log was printed
const logs = await browser.log()
expect(
logs.some((log) => log.message === 'error caught in user code')
).toBe(true)
})
if (isNextStart) { if (isNextStart) {
it('should not expose action content in sourcemaps', async () => { it('should not expose action content in sourcemaps', async () => {
const sourcemap = ( const sourcemap = (
......
'use server'
export async function getServerData() {
return Math.random()
}
export async function badAction() {
throw new Error('oops')
}
'use client'
import { useTransition, useState } from 'react'
import { badAction, getServerData } from './actions'
export default function Component() {
const [isPending, startTransition] = useTransition()
const [wasSubmitted, setWasSubmitted] = useState(false)
return (
<>
{wasSubmitted && <div id="submitted-msg">Submitted!</div>}
<button
id="good-action"
disabled={isPending}
onClick={() => {
startTransition(() => {
getServerData()
.catch(() => {
console.log('error caught in user code')
})
.finally(() => {
setWasSubmitted(true)
})
})
}}
>
Submit Action
</button>
<button
id="bad-action"
disabled={isPending}
onClick={() => {
startTransition(() => {
badAction()
.catch(() => {
console.log('error caught in user code')
})
.finally(() => {
setWasSubmitted(true)
})
})
}}
>
Submit Action (Throws)
</button>
</>
)
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment