So, increasingly I encounter this issue:
I have one method call which includes two or more operations. If the first operation is done successfully but not the latter one(s); naturally there’s an error returning as if the entire operation failed; like this:
So in this scenario, if say the email credentials were changed but not updated; it may fail; whereas Collection does update. Then the error returned to the client is that the operation couldn’t be done whereas it was actually done but just couldn’t send the email…
I’m looking for the best practices to follow for this case and as you may well know; it can get very complex. Perhaps I need to change the whole way I architect these??
Due to the characteristics of MongoDB especially; there’s a lot of places where we duplicate data (just think of updating another collection in addition to the first one). So I think there must be quite intelligent ways to handle this issue and I’m aware it is not only about error management indeed…
Thanks.
Though I need a bit more articulated answer please.
If not try catch, what pattern is better? And why to avoid try catch?
Handling error per operation means writing separate functions/methods for every each operation, and I would in that case save errors somewhere if not needed to send to client to user. Indeed I’d need to save errors somewhere in all cases. For that, do you have any suggestions?
try-catch pattern is a one-size fits all handling. If all you wanted is to catch the error and do something the same way with any error you catch, then that will do.
But normally, with what you have posted in your initial post, there are specific behavior you wanted to do if there is a specific error. Also, different systems (like database or email servers) behaves differently, and most of the time, their respective APIs handles error differently. And yes, some APIs do not even throw errors.
In my case, I only use try-catch block to catch unknown behaviors i.e. behavior that I do not expect especially coming from 3rd party systems.
I’m still curious what different approaches are regarding making best error handling practices. Mainly I’m interested in handling two different mongodb collection updates within one operation. I guess a nested try catch will do but I’m interested in knowing better patterns and avoid issues…
Unlike the example in the docs, I use async/await instead of blocking with while (true), and export a wrapInTransaction function. I’m using it for database migrations at the moment.
It needs a little bit of work to work for Methods. You need to get a raw mongodb client object to pass in, and you’ll want to bind this as well