In my TRPC app, I have a service that we use that does something like this:
export class MyCustomService {
public myCustomMethod() {
throw new MyCustomError('I am a custom error message!')
}
}
and my TRPC router looks like:
export const appRouter = router({
methodName: publicProcedure.query(() => {
myCustomService.myCustomMethod()
})
})
And I have a function that handles errors:
export const standardTrpcErrorHandler = (error: Error): TRPCError => {
if (errorinstanceof MyCustomError) {
return new TRPCError({
...error,
code: 'NOT_FOUND',
message: error.message,
})
}
return new TRPCError({
...error,
code: 'INTERNAL_SERVER_ERROR',
message: error.message,
})
}
And I want to globally apply this logic to error handling. However, from all documentation I can find, the only way to apply logic like this is within the errorFormatter
method where TRPC has already translated it to a TRPCError. This would be fine, but I don’t want to manually add 404 to the shape
response here, and let that be handled by TRPC normally. I also cannot throw a TRPCError from my service’s method, since that method lives outside the scope of the TRPC router.
Where would I add this logic?