I’m writing a data processing system in Node.js.
Pieces of data are user provided or come from outside sources, so
- they can be malformed in various ways;
- they can be ambiguous;
- they can be contradictory to each other.
In those cases I generally want to alert user about it and then:
- if the system is used in interactive mode (i.e. data is entered in REPL) the processing should stop, suggest some actions and wait for user’s decision.
- if it runs in batch mode (i.e. data comes from files, web services or similar sources) I want to continue processing discarding this pieces of information.
Of course the method of alerting user also depends on mode.
I thought that exceptions are right solution for this kind of problem, because:
- malformed or contradictory data should be an exception;
- this way code for exceptional behavior will be visibly separated from usual flow;
- I’ll be able to bubble exceptions to higher level, on which I can decide what exactly to do with it.
So I started to look for guides and found two relevant things:
- This comment by @Raynos Node.js Best Practice Exception Handling ;
- http://codebetter.com/karlseguin/2010/01/25/don-t-use-try-catch/.
The former is without further explanation. The later I understand, but I think it’s not my case.
How would you address this? I’m looking for general approach, not necessarily platform or language specific… or is there anything especially evil in JavaScript try-catch?
It is true that try { } catch { } finally { } has limited usefulness in standard node, and error handling can be problematic.
However In a project I was recently on, I used these node modules: Fibers, Fibers-Promise in a way where effectively, I could do something akin to Thread.join on async callbacks, and making it possible to use node in a procedural, rather than functional style.
There are tradeoffs. Fibers / all co-routine libraries modify node’s core code, making it impossible to use on the front end. But depending on your purposes, you might want to look into this.