fix: error handling in fs routes (#2474)
Ran into an issue where we weren't responding with the correct status code and passed response headers. This was a bit of a rabbit hole and it was caused by us wrapping to more error handling middlewares than necessary.
This commit is contained in:
@@ -470,3 +470,19 @@ Deno.test("FreshApp - sets error on context", async () => {
|
||||
expect(thrown[0][0]).toEqual(thrown[0][1]);
|
||||
expect(thrown[1][0]).toEqual(thrown[1][1]);
|
||||
});
|
||||
|
||||
Deno.test("FreshApp - support setting request init in ctx.render()", async () => {
|
||||
const app = new App<{ text: string }>()
|
||||
.get("/", (ctx) => {
|
||||
return ctx.render(<div>ok</div>, {
|
||||
status: 416,
|
||||
headers: { "X-Foo": "foo" },
|
||||
});
|
||||
});
|
||||
|
||||
const server = new FakeServer(await app.handler());
|
||||
const res = await server.get("/");
|
||||
await res.body?.cancel();
|
||||
expect(res.status).toEqual(416);
|
||||
expect(res.headers.get("X-Foo")).toEqual("foo");
|
||||
});
|
||||
|
||||
+5
-1
@@ -170,7 +170,11 @@ export class FreshReqContext<State>
|
||||
: new Headers();
|
||||
|
||||
headers.set("Content-Type", "text/html; charset=utf-8");
|
||||
const responseInit: ResponseInit = { status: init.status ?? 200, headers };
|
||||
const responseInit: ResponseInit = {
|
||||
status: init.status ?? 200,
|
||||
headers,
|
||||
statusText: init.statusText,
|
||||
};
|
||||
|
||||
let partialId = "";
|
||||
if (this.url.searchParams.has("fresh-partial")) {
|
||||
|
||||
@@ -127,7 +127,7 @@ export function getCodeFrame(stack: string, rootDir: string) {
|
||||
file.line - 1,
|
||||
file.column - 1,
|
||||
);
|
||||
} catch (err) {
|
||||
} catch {
|
||||
// Ignore
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,7 +66,7 @@ Deno.test(
|
||||
.use(async (ctx) => {
|
||||
try {
|
||||
return await ctx.next();
|
||||
} catch (err) {
|
||||
} catch {
|
||||
return ctx.render(<p>ok</p>);
|
||||
}
|
||||
})
|
||||
|
||||
+4
-6
@@ -3,8 +3,8 @@ import type { Method } from "./router.ts";
|
||||
|
||||
export interface PageResponse<T> {
|
||||
data: T;
|
||||
headers: Headers;
|
||||
status: number;
|
||||
headers?: HeadersInit;
|
||||
status?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -42,10 +42,8 @@ export function page<T>(data?: T, options?: {
|
||||
}): PageResponse<T> {
|
||||
return {
|
||||
data: data ?? undefined as T,
|
||||
headers: options?.headers instanceof Headers
|
||||
? options.headers
|
||||
: new Headers(options?.headers),
|
||||
status: options?.status ?? 200,
|
||||
headers: options?.headers,
|
||||
status: options?.status,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -156,6 +156,8 @@ export async function fsRoutes<State>(
|
||||
const stack: InternalRoute<State>[] = [];
|
||||
let hasApp = false;
|
||||
|
||||
const specialPaths = new Set<string>();
|
||||
|
||||
for (let i = 0; i < routeModules.length; i++) {
|
||||
const routeMod = routeModules[i];
|
||||
const normalized = routeMod.path;
|
||||
@@ -246,10 +248,15 @@ export async function fsRoutes<State>(
|
||||
}
|
||||
let parent = mod.path.slice(0, -"_error".length);
|
||||
parent = parent === "/" ? "*" : parent + "*";
|
||||
app.all(
|
||||
parent,
|
||||
errorMiddleware(errorComponents, handler),
|
||||
);
|
||||
|
||||
// Add error route as it's own route
|
||||
if (!specialPaths.has(mod.path)) {
|
||||
specialPaths.add(mod.path);
|
||||
app.all(
|
||||
parent,
|
||||
errorMiddleware(errorComponents, handler),
|
||||
);
|
||||
}
|
||||
middlewares.push(errorMiddleware(errorComponents, handler));
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -941,6 +941,94 @@ Deno.test("fsRoutes - async route components returning response", async () => {
|
||||
expect(text).toEqual("index");
|
||||
});
|
||||
|
||||
Deno.test(
|
||||
"fsRoutes - returns response code from error route",
|
||||
async () => {
|
||||
const server = await createServer<{ text: string }>({
|
||||
"routes/_app.tsx": {
|
||||
default: (ctx) => {
|
||||
return (
|
||||
<div>
|
||||
_app/<ctx.Component />
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
"routes/_error.tsx": {
|
||||
default: () => <div>fail</div>,
|
||||
},
|
||||
"routes/index.tsx": {
|
||||
default: () => <div>index</div>,
|
||||
},
|
||||
"routes/bar.tsx": {
|
||||
default: () => <div>index</div>,
|
||||
},
|
||||
"routes/foo/index.tsx": {
|
||||
default: () => <div>foo/index</div>,
|
||||
},
|
||||
"routes/foo/_error.tsx": {
|
||||
default: () => {
|
||||
throw new Error("fail");
|
||||
},
|
||||
},
|
||||
"routes/foo/bar.tsx": {
|
||||
default: () => <div>foo/index</div>,
|
||||
},
|
||||
});
|
||||
|
||||
let res = await server.get("/fooa");
|
||||
await res.body?.cancel();
|
||||
expect(res.status).toEqual(404);
|
||||
|
||||
res = await server.get("/foo/asdf");
|
||||
await res.body?.cancel();
|
||||
expect(res.status).toEqual(500);
|
||||
},
|
||||
);
|
||||
|
||||
Deno.test(
|
||||
"fsRoutes - set headers from handler",
|
||||
async () => {
|
||||
const server = await createServer<{ text: string }>({
|
||||
"routes/index.tsx": {
|
||||
handler: (ctx) => {
|
||||
return ctx.render(<h1>hello</h1>, {
|
||||
headers: { "X-Foo": "123" },
|
||||
status: 418,
|
||||
statusText: "I'm a fresh teapot",
|
||||
});
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await server.get("/");
|
||||
await res.body?.cancel();
|
||||
expect(res.status).toEqual(418);
|
||||
expect(res.statusText).toEqual("I'm a fresh teapot");
|
||||
expect(res.headers.get("X-Foo")).toEqual("123");
|
||||
},
|
||||
);
|
||||
|
||||
Deno.test("fsRoutes - set request init from handler #2", async () => {
|
||||
const server = await createServer({
|
||||
"routes/index.tsx": {
|
||||
handler: () => {
|
||||
return page("foo", { status: 404, headers: { "X-Foo": "123" } });
|
||||
},
|
||||
default: (ctx) => {
|
||||
// deno-lint-ignore no-explicit-any
|
||||
return <p>{ctx.data as any}</p>;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await server.get("/");
|
||||
const doc = parseHtml(await res.text());
|
||||
expect(doc.body.firstChild?.textContent).toEqual("foo");
|
||||
expect(res.status).toEqual(404);
|
||||
expect(res.headers.get("X-Foo")).toEqual("123");
|
||||
});
|
||||
|
||||
Deno.test("fsRoutes - sortRoutePaths", () => {
|
||||
let routes = [
|
||||
"/foo/[id]",
|
||||
|
||||
@@ -2,6 +2,7 @@ import { type AnyComponent, h, type RenderableProps, type VNode } from "preact";
|
||||
import type { MiddlewareFn } from "../../middlewares/mod.ts";
|
||||
import type { HandlerFn, PageResponse } from "../../handlers.ts";
|
||||
import type { FreshReqContext, PageProps } from "../../context.ts";
|
||||
import { HttpError } from "../../error.ts";
|
||||
|
||||
export type AsyncAnyComponent<P> = {
|
||||
(
|
||||
@@ -20,6 +21,7 @@ export function renderMiddleware<State>(
|
||||
| AsyncAnyComponent<PageProps<unknown, State>>
|
||||
>,
|
||||
handler: HandlerFn<unknown, State> | undefined,
|
||||
init?: ResponseInit | undefined,
|
||||
): MiddlewareFn<State> {
|
||||
return async (ctx) => {
|
||||
let result: PageResponse<unknown> | undefined;
|
||||
@@ -63,6 +65,23 @@ export function renderMiddleware<State>(
|
||||
}
|
||||
}
|
||||
|
||||
return ctx.render(vnode!);
|
||||
let status: number | undefined = init?.status ?? result?.status;
|
||||
if (
|
||||
ctx.error !== null && ctx.error !== undefined
|
||||
) {
|
||||
if (
|
||||
ctx.error instanceof HttpError
|
||||
) {
|
||||
status = ctx.error.status;
|
||||
} else {
|
||||
status = 500;
|
||||
}
|
||||
}
|
||||
|
||||
return ctx.render(vnode!, {
|
||||
status,
|
||||
statusText: init?.statusText,
|
||||
headers: init?.headers ?? result?.headers,
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
@@ -104,7 +104,7 @@ Deno.test("renderMiddleware - async components Response bail out", async () => {
|
||||
</div>
|
||||
);
|
||||
},
|
||||
async (ctx) => {
|
||||
async () => {
|
||||
await delay(1);
|
||||
|
||||
return new Response("foo");
|
||||
|
||||
@@ -26,12 +26,10 @@ import {
|
||||
import type { BuildCache } from "../../build_cache.ts";
|
||||
import { BUILD_ID } from "../build_id.ts";
|
||||
import { DEV_ERROR_OVERLAY_URL } from "../../constants.ts";
|
||||
import {
|
||||
getCodeFrame,
|
||||
} from "../../dev/middlewares/error_overlay/code_frame.tsx";
|
||||
import * as colors from "@std/fmt/colors";
|
||||
import { escape as escapeHtml } from "@std/html";
|
||||
import { HttpError } from "../../error.ts";
|
||||
import { getCodeFrame } from "../../dev/middlewares/error_overlay/code_frame.tsx";
|
||||
|
||||
const enum OptionsType {
|
||||
ATTR = "attr",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect } from "preact/hooks";
|
||||
import { useSignal } from "@preact/signals";
|
||||
|
||||
export function EscapeIsland(props: { str: string }) {
|
||||
export function EscapeIsland(_props: { str: string }) {
|
||||
const active = useSignal(false);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -225,7 +225,7 @@ Deno.test({
|
||||
|
||||
await withBrowserApp(app, async (page, address) => {
|
||||
let didError = false;
|
||||
page.addEventListener("pageerror", (ev) => {
|
||||
page.addEventListener("pageerror", () => {
|
||||
didError = true;
|
||||
});
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { PageProps } from "@fresh/core";
|
||||
import Header from "../../components/Header.tsx";
|
||||
|
||||
export default function Layout({ Component, state }: PageProps) {
|
||||
export default function Layout({ Component }: PageProps) {
|
||||
return (
|
||||
<>
|
||||
<Header active="" title="" />
|
||||
|
||||
Reference in New Issue
Block a user