I've been working on a growing codebase and I feel like my approach to error handling isn't cutting it anymore. I've looked online for guidance, but I can't seem to find a thorough discussion on it. I'm using React Query and tRPC, but I think these ideas could apply to any tech stack. Currently, I attach an error ID and a message to the error response from the API, then use that ID on the client to determine the specific error that occurred and display the appropriate message.
My workflow looks like this:
1. Receive an error response from the API.
2. For React Query mutations, I handle the error in an `onError` callback.
3. I check to see if the error has an ID, since it's just an Error (not necessarily from the API). For that, I use a helper function.
4. I then have a switch case on `error.id` to create specific error messages for known cases, with a generic fallback if the ID doesn't match any expected ones. All error IDs are stored in an enum.
This seems clunky to me, and I've been thinking about creating a custom error class (like `CustomError`) that would include all the metadata I need (ID, message, etc.) when a fetch fails. I'd prefer to check `if (err instanceof CustomError)` instead of handling it this way.
Is this a poor design choice? Do any of you could share best practices for error handling in full-stack applications? Also, do you prefer sending error messages from the API or handling them client-side? If you're using IDs, do you maintain a unified object or enum for mapping error IDs to messages or functions for message generation? I appreciate any insights!
1 Answer
If the error originates from the server, the best approach is to send a customized error response directly from there. It could look something like `{status: false, reasonCode: 1234, reason: "foo bar failed sending. Try again", uuid: "1234-1234-1234"}`. If you need to format it further on the client, that could keep your process simpler. We use PHP with Vue and have found this method effective without any substantial issues.
That's a good point! However, in some cases, the client may need to dynamically create parts of the error message, like including a user's local time. So, then you must send the relevant UTC time in the error, which the client can then convert.