Vanilla Client Error Handling
What is the right way to handle errors when using the vanilla client?
If I setup a client like so:
And execute a mutation like so:
How should I handle errors? If I try to directly catch when calling the mutate function, the error is typed as
any
Is there a way to type narrow the error at runtime? On the server side, I am using the errorFormatter
to add a custom field to my errors:
My current approach will be to use a runtime validation library like zod to check if this custom field exists on the error
But this is clearly not ideal. Is this the right/best way to approach error handling with the vanilla client, or is there a better approach?Solution:Jump to solution
There is actually a docs page on this, does that answer the question? https://trpc.io/docs/client/vanilla/infer-types#infer-trpcclienterror-types
Inferring Types | tRPC
It is often useful to access the types of your API within your clients. For this purpose, you are able to infer the types contained in your AppRouter.
6 Replies
I would also like to understand this... I also want to handle error centrally...
for example if backend gives an unauthorised error (maybe due to token expiry)... Need to logout the user from frontend & bring the user back to their existing state once they login....
@Krishna Agreed, global handling of certain errors (especially authentication/token expiry), is exactly what my next question would be once I understand how to best handle errors in the most basic case.
Solution
There is actually a docs page on this, does that answer the question? https://trpc.io/docs/client/vanilla/infer-types#infer-trpcclienterror-types
Inferring Types | tRPC
It is often useful to access the types of your API within your clients. For this purpose, you are able to infer the types contained in your AppRouter.
also interested in knowing what the best solution for globally handling errors when using
createTRPCProxyClient
is. I found this discussion https://github.com/trpc/trpc/discussions/2036 but none of the solutions there seem to really be what I want. I'd like to be able to return custom responses to the client like 302 redirects on auth failures and such, but it seems like only createTRPCNext
really supports that with its responseMeta
field.This is perfect! Thank you
@Krishna @justindgm How do you handle errors centrally ?
Ive been trying this but the
redirect
does not seem to run