Skip to content

Commit 0b3546f

Browse files
feat: support overwriting default 404 handler (#3081)
Fixes #1918
1 parent ec2bb17 commit 0b3546f

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

src/app.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,13 @@ export class App<State> {
242242
return this;
243243
}
244244

245-
handler(): (
245+
/**
246+
* Create handler function for `Deno.serve` or to be used in
247+
* testing.
248+
* @param {() => Promise<Response>} [nextFn] overwrite default 404 handler
249+
* @returns {Deno.ServeHandler}
250+
*/
251+
handler(nextFn?: () => Promise<Response>): (
246252
request: Request,
247253
info?: Deno.ServeHandlerInfo,
248254
) => Promise<Response> {
@@ -273,7 +279,7 @@ export class App<State> {
273279

274280
const next = matched.patternMatch && !matched.methodMatch
275281
? DEFAULT_NOT_ALLOWED_METHOD
276-
: DEFAULT_NOT_FOUND;
282+
: nextFn ?? DEFAULT_NOT_FOUND;
277283

278284
const { params, handlers, pattern } = matched;
279285
const ctx = new FreshReqContext<State>(

src/app_test.tsx

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -532,3 +532,15 @@ Deno.test("FreshApp - adding Island should convert to valid export names", () =>
532532
fn: component3,
533533
});
534534
});
535+
536+
Deno.test("FreshApp - overwrite default 404 handler", async () => {
537+
const app = new App().get("/foo", () => new Response("foo"));
538+
539+
const server = new FakeServer(
540+
app.handler(() => Promise.resolve(new Response("bar"))),
541+
);
542+
543+
const res = await server.get("/invalid");
544+
const text = await res.text();
545+
expect(text).toEqual("bar");
546+
});

0 commit comments

Comments
 (0)