DCsan
DCsan•2y ago

pattern for handling failed TXs

if i have a DB mutation that fails, eg buying something but the user doesn't have enough balance... is there a simple way to handle this? eg can a useMutation return a value? should I 'throw' inside the mutation fn and then catch in the main client code? what other options are there? I'd prefer to avoid something like a totally different out-of-band "errors" list
5 Replies
jamwt
jamwt•2y ago
Returning a value is recommended! Throwing also works, but for common errors, probably best to just have an operation status returned. Be aware though that if you want earlier db changes rolled back, you need to throw.
ballingt
ballingt•2y ago
+1 to Jamie, in production we're going to start stripping error messages soon so while you can throw an error on the server and see the error message on the client today, in production we'll soon be stripping these for privacy If you want to be able to throw an error deep in a helper function and get a useful response, I'd recommend using a try/catch in your mutation and then returning a different value based on success for failure. In the future we'll provide a special error you can throw that does send data to the client, since it can be convenient to abort a transaction from deep in the call stack.
DCsan
DCsanOP•2y ago
i recall go has some other method for dealing with this and avoiding try/catch. just looking for a common pattern. returning a struct with {ok: false, ...} seems a normal http way to go?
ballingt
ballingt•2y ago
Yeah that's great, TypeScript does a nice job with things like
type Response = { ok: true, data: string[] } | { ok: false, reason: string }
type Response = { ok: true, data: string[] } | { ok: false, reason: string }
Michal Srb
Michal Srb•2y ago
The current advice is captured in the docs (with additional details): https://docs.convex.dev/functions/error-handling Let us know if you have any feedback on the docs 🙂
Error Handling | Convex Developer Hub
There are two reasons why your Convex

Did you find this page helpful?