Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { createServerFn } from '@tanstack/react-start'
3import { setResponseStatus } from '@tanstack/react-start/server'
4import { useState } from 'react'
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] = useState<any>(null)
25 const [invalidResponse, setInvalidResponse] = useState<CustomError | null>(
26 null,
27 )
28β
29 return (
30 <div>
31 <button
32 data-testid="server-function-valid-input"
33 onClick={() =>
34 serverFnThrowing({ data: { hello: 'world' } }).then(setValidResponse)
35 }
36 >
37 trigger valid input
38 </button>
39 <div data-testid="server-function-valid-response">
40 {JSON.stringify(validResponse)}
41 </div>
42β
43 <br />
44 <button
45 data-testid="server-function-invalid-input"
46 onClick={() =>
47 serverFnThrowing({ data: { hello: 'error' } }).catch((err) => {
48 if (err instanceof CustomError) {
49 setInvalidResponse(err)
50 } else {
51 throw new Error('expected CustomError')
52 }
53 })
54 }
55 >
56 trigger invalid input
57 </button>
58 <div data-testid="server-function-invalid-response">
59 {invalidResponse
60 ? JSON.stringify({
61 message: invalidResponse.message,
62 foo: invalidResponse.foo,
63 bar: invalidResponse.bar.toString(),
64 })
65 : JSON.stringify(validResponse)}
66 </div>
67 </div>
68 )
69}