Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

custom-error.tsx

68 lines2.0 KB

1import { createFileRoute } from '@tanstack/solid-router'
2import { createServerFn } from '@tanstack/solid-start'
3import { setResponseStatus } from '@tanstack/solid-start/server'
4import { createSignal } from 'solid-js'
5import { z } from 'zod'
6import { CustomError } from '~/CustomError'
7​
8const schema = z.object({ hello: z.string() })
9const serverFnThrowing = createServerFn()
10 .validator(schema)
11 .handler(async ({ data }) => {
12 if (data.hello === 'world') {
13 return 'Hello, world!'
14 }
15 setResponseStatus(499)
16 throw new CustomError('Invalid input', { foo: 'bar', bar: BigInt(123) })
17 })
18​
19export const Route = createFileRoute('/server-function/custom-error')({
20 component: RouteComponent,
21})
22​
23function RouteComponent() {
24 const [validResponse, setValidResponse] = createSignal<any>(null)
25 const [invalidResponse, setInvalidResponse] =
26 createSignal<CustomError | null>(null)
27​
28 return (
29 <div>
30 <button
31 data-testid="server-function-valid-input"
32 onClick={() =>
33 serverFnThrowing({ data: { hello: 'world' } }).then(setValidResponse)
34 }
35 >
36 trigger valid input
37 </button>
38 <div data-testid="server-function-valid-response">
39 {JSON.stringify(validResponse())}
40 </div>
41​
42 <br />
43 <button
44 data-testid="server-function-invalid-input"
45 onClick={() =>
46 serverFnThrowing({ data: { hello: 'error' } }).catch((err) => {
47 if (err instanceof CustomError) {
48 setInvalidResponse(err)
49 } else {
50 throw new Error('expected CustomError')
51 }
52 })
53 }
54 >
55 trigger invalid input
56 </button>
57 <div data-testid="server-function-invalid-response">
58 {invalidResponse()
59 ? JSON.stringify({
60 message: invalidResponse()?.message,
61 foo: invalidResponse()?.foo,
62 bar: invalidResponse()?.bar.toString(),
63 })
64 : JSON.stringify(invalidResponse())}
65 </div>
66 </div>
67 )