Theo's Typesafe CultTTC
Theo's Typesafe Cult3y ago
5 replies
test_1

how to handle tRPC errors with mutationAsync on my react frontend?

im trying to convert this component to use tRPC mutation https://pastebin.com/4sJKCULW
here is what I have so far
https://pastebin.com/6Hph40Ur

this is the backend route
    createUser:
        t.procedure
            .input(
                z.object({
                    username: z.string(),
                    password: z.string()
                })
            )
            .mutation(async (opts) => {
                const { input } = opts
                const user = await prisma.user.create({ data: input })
                return user
            }),


I am not getting consistent errors, for example in the screenshots u can see a prisma unique constraint and a zod error from the backend, they both have different structures unfortunately
to get the message from the zod, I have to JSON.parse and then do something like message[0].message which doesnt seem intuitive

so how would I handle errors in my try catch ? also what type do I give the error block?
        } catch (error: any) {
            console.log("<> <> <> ERROR CAUGHT <> <> <> : ", typeof error, Array.isArray(error))
            console.log(error)
            setCreateFormInfo("error caught: " + error.message)
        }


also while im here, how do i get the zod validation from backend to do frontend validation as well before sending fetch?
and also doing const data = await res feels wrong to me
any tips appreciated in converting this very simple component, thanks
image.png
image.png
Pastebin
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Was this page helpful?