Skip to content

Middleware does not catch error thrown by serverFn #6381

@esoteloferry

Description

@esoteloferry

Which project does this relate to?

Start

Describe the bug

Hi ,

First of all, Thanks for the project!.

I have an issue with middleware catching errors thrown by server fn. I have a server function that uses a middleware. That middleware try catch the next() to hide possible leak of information thrown by unhandled errors.
But for my surprise, the thrown error is not caught.

Note: I also tried WITH and WITHOUT await (...return await next()....) .Some examples in docs, show return next without awaiting.

export const Route = createFileRoute("/")({
	component: App,
	loader: async () => getName(),
});

const middleware = createMiddleware().server(async ({ next }) => {
	try {
		return await next();
	} catch (error) {
		console.error("Middleware caught an error:", error);
		return new Response("An error occurred while processing your request.", {
			status: 500,
		});
	}
});

const getName = createServerFn()
	.middleware([middleware])
	.handler(async () => {
		throw new Error("This message should be caught by middleware");
		// return "TanStack Start";
	});

function App() {
	const name = Route.useLoaderData();
	console.log("Name is ", name);
return <div>hi</div>
}

Your Example Website or App

https://github.com/esoteloferry/tanstackstart-bug-catch-middleware

Steps to Reproduce the Bug or Issue

  1. Git clone minimal reproduction repro https://github.com/esoteloferry/tanstackstart-bug-catch-middleware
  2. npm i
  3. npm run dev
  4. check localhost:3000

Expected behavior

I would suspect error message would be "An error occurred while processing your request." , which is the error message in the catch of middleware.

Screenshots or Videos

Image

Platform

  • Router / Start Version:v1.149.3
  • OS: macOS
  • Browser:Chrome
  • Browser Version: 143.0.7499.193
  • Bundler: vite
  • Bundler Version: 7.3.1

Additional context

This used to work, I think in v1.143 . Not sure.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions