correct way to handle errors run time errors

I want to handle errors, for example when executing this mutation an error appears
"use client";
etc
const mutationAdd = trpc.user.addUser.useMutation({
onSuccess: async (data) => {
await utils.user.getUsers.refetch();
router.push("/admin/all-employees");
},
onError: (error) => {
toast({
variant: "destructive",
action: <ToastAction altText="Try again">{error.message}</ToastAction>,
});
return;
},
});
"use client";
etc
const mutationAdd = trpc.user.addUser.useMutation({
onSuccess: async (data) => {
await utils.user.getUsers.refetch();
router.push("/admin/all-employees");
},
onError: (error) => {
toast({
variant: "destructive",
action: <ToastAction altText="Try again">{error.message}</ToastAction>,
});
return;
},
});
server router
addUser: publicProcedure
.input(
z.object({
username: z.string(),
name: z.string(),
email: z.string().email(),
password: z
.string()
.min(5, "password should be at least 5 digits long."),
role: z.string(),
})
)
.mutation(async ({ input }) => {
const newUser = await auth.api.createUser({
headers: await headers(),
body: {
name: input.name,
email: input.email,
password: input.password,
role: input.role,
data: {
username: input.username,
},
},
});
return newUser;
}),
addUser: publicProcedure
.input(
z.object({
username: z.string(),
name: z.string(),
email: z.string().email(),
password: z
.string()
.min(5, "password should be at least 5 digits long."),
role: z.string(),
})
)
.mutation(async ({ input }) => {
const newUser = await auth.api.createUser({
headers: await headers(),
body: {
name: input.name,
email: input.email,
password: input.password,
role: input.role,
data: {
username: input.username,
},
},
});
return newUser;
}),
No description
5 Replies
codecret | Software Engineer
the toast is working but at the same time i get an error
FluX
FluX6d ago
codecret | Software Engineer
thanks for answering , actually i wonder if this error will be shown in production environement because in the bottom it's noted
No description
Nick
Nick6d ago
How are you calling the mutation? I bet you're calling mutateAsync() in a event callback and not catching it, so the console log is correct just use mutate() if you don't intend to handle the error in the callback
codecret | Software Engineer
thank youu

Did you find this page helpful?