wleistra
wleistraβ€’13mo ago

Axios, ExpressMiddleware and TRPCErrors

We have an express based TRPC server and our procedures are calling our endpoints using axios. So when our users credentials provided expired or are incorrect Axios will return with a 401 as it should. I need to get this UNAUTHORIZED 401 error to the frontend but no matter what I try TRPC throws is as a 500 INTERNAL_SERVER_ERROR. I tried error formatter and on error and I hoped to get the httpStatus code from the axios error somehow but I only get access to the message. Can someone here be so kind and point me in the right direction to forward the errors from our Axios Instances as such to the React TRPC client. πŸ™
2 Replies
test_1
test_1β€’13mo ago
did u try something like throw TRPCError({ code: "UNAUTHORIZED"
wleistra
wleistraβ€’13mo ago
The issue I'm having is that I cannot access the error response from axios in OnError or ErrorFormatter to base any robust logic to throw the trpcError with unauthorized code. What I would like to avoid is rely on the error message and do some kind of if string of message includes 401... So I was hoping there would be another way or some way to work with the error (httpStatus) from Axios that TRPC receives. I found a solution. The cause key on the error object was my Axios error, and after an isAxiosError check, it can be cast as such, and there I get the actual response from my Axios query. So now I could use the errorFormatter on context creation to return those codes to the client instead of the previous 500/INTERNAL_SERVER_ERROR generic error seen there.