rd
rd16mo ago

Throwing fastify errors when using fastify adapter

Hello, I'm using fastifyTRPCPlugin from @trpc/server/adapters/fastify and trying to throw errors correctly. I usually use @fastify-sensible because I find the API clear, e.g. I can write things like fastify.httpErrors.forbidden() or fastify.httpErrors.unauthorized. However if I throw one of these in a tRPC procedure it seems the error code is always 500, assuming that's because tRPC is intercepting/handling them in some way? What's the best way to "solve" this? Thanks!
2 Replies
Nick
Nick16mo ago
You shouldn’t be throwing fastify errors in services is the brutal answer. The more helpful answer is you could write a middleware which catches them and wraps them up in a TRPCError as the cause, then you can use an errorFornatter to propagate them in whatever shape you like to the frontend
rd
rd16mo ago
Ace, I assumed as much and went ahead and did something similar earlier, but good to have confirmation. It's sometimes difficult to know with adapters which part to prioritise so just wanted some clarification, thanks!