From 9039f892ca70fefc43a541d98a9f5b440f78256b Mon Sep 17 00:00:00 2001 From: Matthew Davis Date: Fri, 20 Dec 2024 21:30:55 -0600 Subject: [PATCH] 404 handling documentation --- readme.md | 28 ++++++++++++++++++++++++++++ test/app/src/app.svelte | 8 +++++++- test/app/src/lib/not-found.svelte | 1 + 3 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 test/app/src/lib/not-found.svelte diff --git a/readme.md b/readme.md index bc4e826..d6b524a 100644 --- a/readme.md +++ b/readme.md @@ -34,6 +34,7 @@ npm install @mateothegreat/svelte5-router - [Using Components \& Snippets](#using-components--snippets) - [Accessing Parameters](#accessing-parameters) - [Passing Props](#passing-props) + - [Not Found](#not-found) - [Hooks](#hooks) - [States](#states) - [Navigation State](#navigation-state) @@ -195,6 +196,33 @@ Then, in your component, you can access the prop like this:
{JSON.stringify(myProps, null, 2)}
``` +### Not Found + +To handle 404 errors, you can use the `.*` or `.+` pattern such as: + +```ts +const routes: Route[] = [ + // This will match the root path ("/") and render the Homepage component: + { + path: "^/$", + component: Homepage + }, + { + path: "profile", + component: Profile + }, + // This will match any path that is not found: + { + path: ".+", + component: NotFound + } +]; +``` + +Notice the `^/$` pattern. This matches the root path ("/")indicating that this is the first "default" route. + +Now, after this route, we have a catch-all route that matches any path at last indicating the route is not found. + ## Hooks Use `pre` and `post` hooks to run before and after a route is rendered to do things like authentication, logging, etc. diff --git a/test/app/src/app.svelte b/test/app/src/app.svelte index 0bd26de..f0c44d0 100644 --- a/test/app/src/app.svelte +++ b/test/app/src/app.svelte @@ -4,6 +4,7 @@ import { Github, Home } from "lucide-svelte"; import Default from "./lib/default.svelte"; import Delayed from "./lib/delayed.svelte"; + import NotFound from "./lib/not-found.svelte"; import Params from "./lib/params/params.svelte"; import Props from "./lib/props/props.svelte"; import BankAccount from "./lib/protected/bank-account.svelte"; @@ -13,7 +14,7 @@ const routes: Route[] = [ { - path: "", + path: "^/$", component: Default }, { @@ -102,6 +103,10 @@ { path: "query-redirect", component: QueryRedirect + }, + { + path: ".+", + component: NotFound } ]; @@ -160,6 +165,7 @@ Call the goto("/a"); method /query-redirect + /not-found
diff --git a/test/app/src/lib/not-found.svelte b/test/app/src/lib/not-found.svelte new file mode 100644 index 0000000..5d27e0f --- /dev/null +++ b/test/app/src/lib/not-found.svelte @@ -0,0 +1 @@ +404 not found :(