Skip to content

Conversation

@jjcantu
Copy link

@jjcantu jjcantu commented Jan 16, 2026

Summary & Purpose

Fixes #6381 - Middleware can now properly catch errors thrown by server function handlers.

Changes

  • packages/start-client-core/src/createServerFn.ts: Modified executeMiddleware to throw errors from result.error instead of silently returning them in context, allowing parent middleware to catch them with try/catch
  • e2e/react-start/server-functions/src/routes/middleware/catch-handler-error.tsx: Added test route demonstrating middleware error catching
  • e2e/react-start/server-functions/tests/server-functions.spec.ts: Added e2e test verifying middleware can catch handler errors

Summary by CodeRabbit

  • New Features

    • Middleware can now intercept and handle errors thrown by server functions, enabling custom error recovery and messaging strategies.
  • Bug Fixes

    • Improved error propagation through middleware stack to ensure errors are properly surfaced to handlers.
  • Tests

    • Added end-to-end test suite verifying middleware error interception and handling capabilities.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 16, 2026

📝 Walkthrough

Walkthrough

This PR fixes a bug where middleware could not catch errors thrown by server functions. It modifies error propagation in the middleware execution layer to allow try/catch blocks in middleware to properly intercept downstream errors, adds a new test route demonstrating the fixed behavior, and includes an end-to-end test verifying the middleware error handling.

Changes

Cohort / File(s) Change Summary
Route generation
e2e/react-start/server-functions/src/routeTree.gen.ts
Adds new route registration for /middleware/catch-handler-error including type declarations and route map entries
Test route implementation
e2e/react-start/server-functions/src/routes/middleware/catch-handler-error.tsx
Implements a new server route with middleware that catches errors from a server function handler and returns a custom result object; includes React component UI for triggering and displaying caught errors
E2E test
e2e/react-start/server-functions/tests/server-functions.spec.ts
Adds test case verifying middleware captures and exposes errors thrown by server function handlers
Middleware error handling
packages/start-client-core/src/createServerFn.ts
Removes try/catch wrapper around next middleware call in executeMiddleware; now explicitly checks result for errors and throws them, allowing outer catch block to intercept downstream errors

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • fix: refactor middleware #5517: Modifies middleware error propagation in packages/start-client-core/src/createServerFn.ts with overlapping changes to executeMiddleware error handling logic

Suggested labels

package: start-client-core

Poem

🐰 A rabbit hops with joy today,
For middleware catches errors on their way!
No more do thrown exceptions hide,
They bubble up with truthful pride,
Safe in the try/catch's embrace. 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: enabling middleware to catch server function handler errors, which aligns directly with the primary objective of fixing issue #6381.
Linked Issues check ✅ Passed The pull request successfully addresses issue #6381 by modifying executeMiddleware to throw errors from result.error so parent middleware can catch them, includes comprehensive e2e coverage demonstrating the fix, and validates the expected behavior.
Out of Scope Changes check ✅ Passed All changes are directly scoped to fixing the middleware error-catching issue: the core fix in createServerFn.ts, a new test route demonstrating the capability, and an e2e test validating the fix. No unrelated modifications detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings


📜 Recent review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 86605e3 and c6a1a85.

📒 Files selected for processing (4)
  • e2e/react-start/server-functions/src/routeTree.gen.ts
  • e2e/react-start/server-functions/src/routes/middleware/catch-handler-error.tsx
  • e2e/react-start/server-functions/tests/server-functions.spec.ts
  • packages/start-client-core/src/createServerFn.ts
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Use TypeScript strict mode with extensive type safety for all code

Files:

  • e2e/react-start/server-functions/src/routes/middleware/catch-handler-error.tsx
  • e2e/react-start/server-functions/src/routeTree.gen.ts
  • packages/start-client-core/src/createServerFn.ts
  • e2e/react-start/server-functions/tests/server-functions.spec.ts
**/*.{js,ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Implement ESLint rules for router best practices using the ESLint plugin router

Files:

  • e2e/react-start/server-functions/src/routes/middleware/catch-handler-error.tsx
  • e2e/react-start/server-functions/src/routeTree.gen.ts
  • packages/start-client-core/src/createServerFn.ts
  • e2e/react-start/server-functions/tests/server-functions.spec.ts
🧠 Learnings (5)
📚 Learning: 2025-09-28T21:41:45.233Z
Learnt from: nlynzaad
Repo: TanStack/router PR: 5284
File: e2e/react-start/basic/server.js:50-0
Timestamp: 2025-09-28T21:41:45.233Z
Learning: In Express v5, catch-all routes must use named wildcards. Use `/*splat` to match everything except root path, or `/{*splat}` (with braces) to match including root path. The old `*` syntax is not allowed and will cause "Missing parameter name" errors. This breaking change requires explicit naming of wildcard parameters.

Applied to files:

  • e2e/react-start/server-functions/src/routes/middleware/catch-handler-error.tsx
  • e2e/react-start/server-functions/src/routeTree.gen.ts
📚 Learning: 2025-12-06T15:03:07.223Z
Learnt from: CR
Repo: TanStack/router PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-06T15:03:07.223Z
Learning: Applies to **/*.{js,ts,tsx} : Implement ESLint rules for router best practices using the ESLint plugin router

Applied to files:

  • e2e/react-start/server-functions/src/routes/middleware/catch-handler-error.tsx
📚 Learning: 2025-12-17T02:17:55.086Z
Learnt from: schiller-manuel
Repo: TanStack/router PR: 6120
File: packages/router-generator/src/generator.ts:654-657
Timestamp: 2025-12-17T02:17:55.086Z
Learning: In `packages/router-generator/src/generator.ts`, pathless_layout routes must receive a `path` property when they have a `cleanedPath`, even though they are non-path routes. This is necessary because child routes inherit the path from their parent, and without this property, child routes would not have the correct full path at runtime.

Applied to files:

  • e2e/react-start/server-functions/src/routeTree.gen.ts
📚 Learning: 2025-10-01T18:31:35.420Z
Learnt from: schiller-manuel
Repo: TanStack/router PR: 5330
File: e2e/react-start/custom-basepath/src/routeTree.gen.ts:58-61
Timestamp: 2025-10-01T18:31:35.420Z
Learning: Do not review files named `routeTree.gen.ts` in TanStack Router repositories, as these are autogenerated files that should not be manually modified.

Applied to files:

  • e2e/react-start/server-functions/src/routeTree.gen.ts
📚 Learning: 2025-10-08T08:11:47.088Z
Learnt from: nlynzaad
Repo: TanStack/router PR: 5402
File: packages/router-generator/tests/generator/no-formatted-route-tree/routeTree.nonnested.snapshot.ts:19-21
Timestamp: 2025-10-08T08:11:47.088Z
Learning: Test snapshot files in the router-generator tests directory (e.g., files matching the pattern `packages/router-generator/tests/generator/**/routeTree*.snapshot.ts` or `routeTree*.snapshot.js`) should not be modified or have issues flagged, as they are fixtures used to verify the generator's output and are intentionally preserved as-is.

Applied to files:

  • e2e/react-start/server-functions/src/routeTree.gen.ts
🧬 Code graph analysis (2)
e2e/react-start/server-functions/src/routes/middleware/catch-handler-error.tsx (1)
packages/start-client-core/src/createServerFn.ts (1)
  • createServerFn (54-188)
e2e/react-start/server-functions/tests/server-functions.spec.ts (1)
e2e/e2e-utils/src/fixture.ts (1)
  • test (18-48)
🔇 Additional comments (6)
e2e/react-start/server-functions/tests/server-functions.spec.ts (1)

887-911: Well-structured e2e test for the middleware error catching fix.

The test correctly verifies:

  1. Middleware catches the handler error (via caught-status)
  2. Original error message is preserved
  3. Middleware provides a handled response
  4. No uncaught error appears in the UI

The absence of whitelistErrors ensures the test will fail if any unhandled errors reach the console, which is the expected behavior when middleware properly catches errors.

e2e/react-start/server-functions/src/routeTree.gen.ts (1)

1-10: Skipping review of auto-generated file.

This file is automatically generated by TanStack Router and should not be manually modified. Based on learnings from this repository.

e2e/react-start/server-functions/src/routes/middleware/catch-handler-error.tsx (3)

5-22: Middleware implementation correctly demonstrates the error catching pattern.

The try/catch around next() is exactly the pattern that the fix in createServerFn.ts enables. The middleware properly catches the handler error and returns a structured result.


24-32: Server function and route definition are correct.

The server function properly attaches the middleware and throws an error for testing purposes. Route definition follows TanStack Router conventions.


34-89: RouteComponent implementation is well-structured for e2e testing.

The component properly manages loading, result, and error states. All test IDs match those used in the e2e test file. The type assertions at lines 19 and 49 are acknowledged in the comment and are acceptable for a test file demonstrating the middleware pattern.

packages/start-client-core/src/createServerFn.ts (1)

269-275: Core fix for middleware error catching looks correct.

The change properly enables middleware to catch errors thrown by downstream handlers/middleware via try/catch. By throwing result.error instead of silently returning it, parent middleware can now intercept and handle errors.

The outer try/catch at lines 310-315 ensures backward compatibility—uncaught errors are still captured and returned in the context for callers that don't use try/catch.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Middleware does not catch error thrown by serverFn

1 participant