Captain
Captainβ€’2y ago

Catch TRPCError, ZoddError on the front-end

i am throwing a TRPCError in a mutation. i dont understand how to catch this error in the OnError method. Please help me with this. i have the following: ServerSide
throw new TRPCError({
message: 'Password changed too recently',
code: 'BAD_REQUEST',
cause: Error("You can only modify your password once a day", { cause: 'VALIDATION_ERROR' }),
});
throw new TRPCError({
message: 'Password changed too recently',
code: 'BAD_REQUEST',
cause: Error("You can only modify your password once a day", { cause: 'VALIDATION_ERROR' }),
});
ClientSide
const { code, message, name, cause, stack } = error as TRPCError

console.log(code, message, name, cause, stack)
const { code, message, name, cause, stack } = error as TRPCError

console.log(code, message, name, cause, stack)
everyting is undefined except for message. but i'd like to include ZodError to the cause. doesn't work either. browser console.
9 Replies
Captain
CaptainOPβ€’2y ago
const error: TRPCError = {
name: "TRPCError",
code: "BAD_REQUEST",
message: "\"password\" must be at least 4 characters"
}

if (error instanceof TRPCError) {
const httpCode = getHTTPStatusCodeFromError(error);
console.log(httpCode); // 400
}
const error: TRPCError = {
name: "TRPCError",
code: "BAD_REQUEST",
message: "\"password\" must be at least 4 characters"
}

if (error instanceof TRPCError) {
const httpCode = getHTTPStatusCodeFromError(error);
console.log(httpCode); // 400
}
the console.log inside the if statement doesnt get printed
Alex / KATT 🐱
Add the actual zod error as the cause in the trpc error instead Then use error.cause
Captain
CaptainOPβ€’2y ago
errors.cause is undefined when on client
Alex / KATT 🐱
On the client? If you want to propagate to the client you need error formatting
Alex / KATT 🐱
Error Formatting | tRPC
The error formatting in your router will be inferred all the way to your client (&Β ReactΒ components)
Alex / KATT 🐱
And it'll be a TRPCClientError
Captain
CaptainOPβ€’2y ago
to want to catch the zod parse error, you actually have to throw a zodError should be included in the docs in my opinion also dont flatten the error when formatting also dont safparse
Alex / KATT 🐱
feel free to improve the docs! πŸ™‚ would love some help! none of the people working on trpc does it as a full-time job
mark salsbery
mark salsberyβ€’2y ago
Good to know! (The first part I mean, I knew the second part)