-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Closed
Description
Description
Function middleware (type: 'function') cannot catch errors from inner middleware/handlers using try/catch. The docs show this pattern, but it doesn't work for function middleware.
Reproduction
// This does NOT work - catch block never fires
const errorMiddleware = createMiddleware({ type: 'function' }).server(async ({ next }) => {
try {
return await next()
} catch (error) {
// Never reached when inner middleware/handler throws
console.log('caught', error)
throw error
}
})Root Cause
In createServerFn.js, userNext catches errors and returns them as { error } instead of throwing:
// Line 154-161
const userNext = async (userCtx = {}) => {
try {
return await callNextMiddleware(nextCtx);
} catch (error) {
return { ...nextCtx, error }; // Returns, doesn't throw
}
};Working Solution
Must check result.error instead:
const errorMiddleware = createMiddleware({ type: 'function' }).server(async ({ next }) => {
const result = await next()
if (result.error) {
// Handle error here
return { ...result, error: new Error('Sanitized message') }
}
return result
})Issues
- Docs show try/catch (observability guide) but that's for request middleware, not function middleware
- TypeScript types don't include
erroron the result - requires cast:(await next()) as { error?: Error } - Ambiguity - unclear when to use try/catch vs result.error
Questions
- Is checking
result.errorthe intended pattern for function middleware error handling? - Should TypeScript types include
errorproperty onFunctionServerResultWithContext? - Should docs clarify the difference between request middleware and function middleware error handling?
Environment
@tanstack/react-start: 1.149.1@tanstack/start-client-core: 1.149.1
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels