Open History to see the last commit
1import { isNotFound } from '@tanstack/router-core'
2import * as Solid from 'solid-js'
3import { CatchBoundary } from './CatchBoundary'
4import { useRouter } from './useRouter'
5import type { NotFoundError } from '@tanstack/router-core'
6β
7// Solid wraps non-Error throws in an Error and stores the original thrown value
8// on `cause`, so component-thrown `notFound()` needs one extra unwrapping step.
9export function getNotFound(
10 error: unknown,
11): (NotFoundError & { isNotFound: true }) | undefined {
12 if (isNotFound(error)) {
13 return error as NotFoundError & { isNotFound: true }
14 }
15β
16 if (isNotFound((error as any)?.cause)) {
17 return (error as any).cause as NotFoundError & { isNotFound: true }
18 }
19β
20 return undefined
21}
22β
23export function CatchNotFound(props: {
24 fallback?: (error: NotFoundError) => Solid.JSX.Element
25 onCatch?: (error: NotFoundError) => void
26 children: Solid.JSX.Element
27}) {
28 const router = useRouter()
29 // TODO: Some way for the user to programmatically reset the not-found boundary?
30 const pathname = Solid.createMemo(() => router.stores.location.get().pathname)
31 const status = Solid.createMemo(() => router.stores.status.get())
32β
33 return (
34 <CatchBoundary
35 getResetKey={() => `not-found-${pathname()}-${status()}`}
36 onCatch={(error) => {
37 const notFoundError = getNotFound(error)
38β
39 if (notFoundError) {
40 props.onCatch?.(notFoundError)
41 } else {
42 throw error
43 }
44 }}
45 errorComponent={({ error }) => {
46 const notFoundError = getNotFound(error)
47β
48 if (notFoundError) {
49 return props.fallback?.(notFoundError)
50 } else {
51 throw error
52 }
53 }}
54 >
55 {props.children}
56 </CatchBoundary>
57 )
58}
59β
60export function DefaultGlobalNotFound() {
61 return <p>Not Found</p>
62}