funki
funki9mo ago

Globally handle specific Error type on backend

Hi, i have a lot of code that's used for both backend and frontend. That's why i'm not throwing TRPCErrors but custom errors instead. They indicate that the error message should be sent to the client if it arises on the backend (on the frontend this obviously doesn't matter). Can i set up the tRPC server side in a way where it will catch all errors so i can do something like this?
if (error instanceof DispatchableError) {
throw new TRPCError({
code: "BAD_REQUEST",
message: error.message,
});
} else {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "Sorry, something went wrong"
})
}
if (error instanceof DispatchableError) {
throw new TRPCError({
code: "BAD_REQUEST",
message: error.message,
});
} else {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "Sorry, something went wrong"
})
}
Solution:
Error formatter is correct, you can omit data or enrich data in there for all your needs 🙂
Jump to solution
4 Replies
funki
funki9mo ago
I'm not sure if errorFormatter is the right thing to use here because this is more of a info/security concern than a formatting one. Because i don't want to leak info to clients about errors i didn't define as DispatchableError.
Solution
Nick
Nick9mo ago
Error formatter is correct, you can omit data or enrich data in there for all your needs 🙂
Nick
Nick9mo ago
You can also use a middleware to pre-handle errors if you like, but the formatter works well for most projects
funki
funki9mo ago
Ok, thanks a lot!