Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/forty-bugs-turn.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"react-router": patch
---

Properly handle ancestor thrown middleware errors before `next()` on fetcher submissions
50 changes: 50 additions & 0 deletions packages/react-router/__tests__/router/context-middleware-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1633,6 +1633,56 @@ describe("context/middleware", () => {
e: new Error("E ERROR"),
});
});

it("throwing from a fetcher action middleware before next bubbles up to the boundary", async () => {
router = createRouter({
history: createMemoryHistory(),
routes: [
{
path: "/",
},
{
id: "a",
path: "/a",
hasErrorBoundary: true,
children: [
{
id: "b",
path: "b",
hasErrorBoundary: false,
middleware: [
({ request }) => {
if (request.method === "POST") {
throw new Error("B ERROR");
}
},
],
action: () => "B",
},
],
},
],
});

// Bubbles to B because it's the initial load and it's loader hasn't run
await router.navigate("/a/b");
expect(router.state.loaderData).toEqual({});
expect(router.state.errors).toBeNull();

let data;
router.subscribe((state) => {
data ??= state.fetchers.get("key")?.data;
});

await router.fetch("key", "b", "/a/b", {
formMethod: "post",
formData: createFormData({}),
});
expect(data).toBeUndefined();
expect(router.state.errors).toEqual({
a: new Error("B ERROR"),
});
});
});
});

Expand Down
11 changes: 11 additions & 0 deletions packages/react-router/lib/router/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2465,6 +2465,17 @@ export function createRouter(init: RouterInit): Router {
);
let actionResult = actionResults[match.route.id];

if (!actionResult) {
// If this error came from a parent middleware before the action ran,
// then it won't be tied to the action route
for (let match of fetchMatches) {
if (actionResults[match.route.id]) {
actionResult = actionResults[match.route.id];
break;
}
}
}

if (fetchRequest.signal.aborted) {
// We can delete this so long as we weren't aborted by our own fetcher
// re-submit which would have put _new_ controller is in fetchControllers
Expand Down