feat: add ctx.renderNotFound() to explicitly render 404 template (#481)

Co-authored-by: Luca Casonato <hello@lcas.dev>
This commit is contained in:
Steven Yung
2022-08-09 19:23:17 +00:00
committed by GitHub
co-authored by Luca Casonato
parent b169d18ecb
commit 49092ed83a
6 changed files with 70 additions and 10 deletions
+36
View File
@@ -8,6 +8,8 @@ Fresh supports customizing the `404 Not Found`, and the
matching route exists, and when a middleware, route handler, or page component
throws an error respectively.
### 404: Not Found
The 404 page can be customized by creating a `_404.tsx` file in the `routes/`
folder. The file must have a default export that is a regular Preact component.
A props object of type `UnknownPageProps` is passed in as an argument.
@@ -22,6 +24,40 @@ export default function NotFoundPage({ url }: UnknownPageProps) {
}
```
#### Manually render 404 pages
The `_404.tsx` file will be invoked automatically when no route matches the URL.
In some cases, one needs to manually trigger the rendering of the 404 page, for
example when the route did match, but the requested resource does not exist.
This can be achieved with `ctx.renderNotFound`.
```tsx
/** @jsx h */
import { h } from "preact";
import { Handlers, PageProps } from "$fresh/server.ts";
export handler: Handlers = {
async GET(req, ctx) {
const blogpost = await fetchBlogpost(ctx.params.slug)
if (!blogpost) {
return ctx.renderNotFound();
}
return ctx.render({ blogpost })
}
}
export default function BlogpostPage({ data }) {
return (
<article>
<h1>{data.blogpost.title}</h1>
{/* rest of your page */}
</article>
);
}
```
### 500: Internal Server Error
The 500 page can be customized by creating a `_500.tsx` file in the `routes/`
folder. The file must have a default export that is a regular Preact component.
A props object of type `ErrorPageProps` is passed in as an argument.
+5 -2
View File
@@ -448,6 +448,8 @@ export class ServerContext {
};
};
const createUnknownRender = genRender(this.#notFound, Status.NotFound);
for (const route of this.#routes) {
const createRender = genRender(route, Status.OK);
if (typeof route.handler === "function") {
@@ -456,6 +458,7 @@ export class ServerContext {
...ctx,
params,
render: createRender(req, params),
renderNotFound: createUnknownRender(req, {}),
});
} else {
for (const [method, handler] of Object.entries(route.handler)) {
@@ -464,12 +467,12 @@ export class ServerContext {
...ctx,
params,
render: createRender(req, params),
renderNotFound: createUnknownRender(req, {}),
});
}
}
}
const unknownHandlerRender = genRender(this.#notFound, Status.NotFound);
const unknownHandler: router.Handler<RouterState> = (
req,
ctx,
@@ -478,7 +481,7 @@ export class ServerContext {
req,
{
...ctx,
render: unknownHandlerRender(req, {}),
render: createUnknownRender(req, {}),
},
);
+1
View File
@@ -65,6 +65,7 @@ export interface HandlerContext<Data = unknown, State = Record<string, unknown>>
extends ConnInfo {
params: Record<string, string>;
render: (data?: Data) => Response | Promise<Response>;
renderNotFound: () => Response | Promise<Response>;
state: State;
}
+10 -8
View File
@@ -24,10 +24,11 @@ import * as $18 from "./routes/layeredMdw/layer2/index.ts";
import * as $19 from "./routes/layeredMdw/layer2/layer3/[id].ts";
import * as $20 from "./routes/layeredMdw/layer2/layer3/_middleware.ts";
import * as $21 from "./routes/middleware_root.ts";
import * as $22 from "./routes/params.tsx";
import * as $23 from "./routes/props/[id].tsx";
import * as $24 from "./routes/static.tsx";
import * as $25 from "./routes/wildcard.tsx";
import * as $22 from "./routes/not_found.ts";
import * as $23 from "./routes/params.tsx";
import * as $24 from "./routes/props/[id].tsx";
import * as $25 from "./routes/static.tsx";
import * as $26 from "./routes/wildcard.tsx";
import * as $$0 from "./islands/Counter.tsx";
import * as $$1 from "./islands/Test.tsx";
import * as $$2 from "./islands/kebab-case-counter-test.tsx";
@@ -56,10 +57,11 @@ const manifest = {
"./routes/layeredMdw/layer2/layer3/[id].ts": $19,
"./routes/layeredMdw/layer2/layer3/_middleware.ts": $20,
"./routes/middleware_root.ts": $21,
"./routes/params.tsx": $22,
"./routes/props/[id].tsx": $23,
"./routes/static.tsx": $24,
"./routes/wildcard.tsx": $25,
"./routes/not_found.ts": $22,
"./routes/params.tsx": $23,
"./routes/props/[id].tsx": $24,
"./routes/static.tsx": $25,
"./routes/wildcard.tsx": $26,
},
islands: {
"./islands/Counter.tsx": $$0,
+7
View File
@@ -0,0 +1,7 @@
import { Handlers } from "../../../server.ts";
export const handler: Handlers = {
GET(_req, ctx) {
return ctx.renderNotFound();
},
};
+11
View File
@@ -392,3 +392,14 @@ Deno.test({
assertEquals(resp.headers.get("server"), "fresh test server");
},
});
Deno.test({
name: "/not_found",
fn: async () => {
const resp = await router(new Request("https://fresh.deno.dev/not_found"));
assert(resp);
assertEquals(resp.status, 404);
const body = await resp.text();
assertStringIncludes(body, "404 not found: /not_found");
},
});