diff --git a/packages/start-server-core/src/createStartHandler.ts b/packages/start-server-core/src/createStartHandler.ts index 60d1c5a8165..a8a6afeeae7 100644 --- a/packages/start-server-core/src/createStartHandler.ts +++ b/packages/start-server-core/src/createStartHandler.ts @@ -495,33 +495,36 @@ function executeMiddleware(middlewares: TODO, ctx: TODO) { const middleware = middlewares[index] if (!middleware) return ctx - const result = await middleware({ - ...ctx, - // Allow the middleware to call the next middleware in the chain - next: async (nextCtx: TODO) => { - // Allow the caller to extend the context for the next middleware - const nextResult = await next({ - ...ctx, - ...nextCtx, - context: { - ...ctx.context, - ...(nextCtx?.context || {}), - }, - }) + let result + try { + result = await middleware({ + ...ctx, + // Allow the middleware to call the next middleware in the chain + next: async (nextCtx: TODO) => { + // Allow the caller to extend the context for the next middleware + const nextResult = await next({ + ...ctx, + ...nextCtx, + context: { + ...ctx.context, + ...(nextCtx?.context || {}), + }, + }) - // Merge the result into the context\ - return Object.assign(ctx, handleCtxResult(nextResult)) - }, - // Allow the middleware result to extend the return context - }).catch((err: TODO) => { + // Merge the result into the context\ + return Object.assign(ctx, handleCtxResult(nextResult)) + }, + // Allow the middleware result to extend the return context + }) + } catch (err: TODO) { if (isSpecialResponse(err)) { - return { + result = { response: err, } + } else { + throw err } - - throw err - }) + } // Merge the middleware result into the context, just in case it // returns a partial context