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
Is there a way to type narrow the error at runtime? On the server side, I am using the
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?
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
anyIs 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
There is actually a docs page on this, does that answer the question? https://trpc.io/docs/client/vanilla/infer-types#infer-trpcclienterror-types
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.