Error handling
We have some trpc routers that make requests to another api - we use axios for that. I'd like to forward these errors to the frontend, so if that api errors with 401, that's what I'd like to see in the browser.
If I just await the request and don't catch the errors, I get a 500 error where the message is the message from the axios request.
What would be the best way to handle this, globally? I wouldn't really want to wrap each api in a try / catch, and I'd also ideally not need to translate those errors to TRPCErrors...
9 Replies
this might give you ideas! https://github.com/trpc/trpc/pull/1652
the keys are to propagate nextjs' ctx object throughout the app & to use
responseMeta
not sure I understand this ๐
. I'm not really talking about SSR specifically. Just a request from the frontend going to a trpc router
I'm testing with:
inside a trpc router. If I log the first clientError inside
responseMeta
like in your example, I'm already seeing a 500 statuscode:
ah i seeeeeee
in the error formatting fn you can do it
Error Formatting | tRPC
The error formatting in your router will be inferred all the way to your client (&ย Reactย components)
instanceof AxiosError
or whatever on the .cause
and then remap it
sorry i misunderstood, sometimes i snap in and out too quickly
potentially you can do it in a middleware too
the thing tho is that a server-to-server call that results in 401 shouldn't necessarily be a 401 for the client
sometimes it should be a 500
just something to keep in mind
so i usually do some mappers further "down" insteadYeah makes sense. Thanks, I'll look into these links โค๏ธ
or do some safe wrapper that is like this
error formatting works, thanks