Node: never use try-catch?

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:

  1. This comment by @Raynos Node.js Best Practice Exception Handling ;
  2. 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.

If it is DATA that you are handling, you might try to think of the app as a message transport.

In this pattern, there cannot be anything to catch, any data that is not understood has a valid message returned to the user - a message saying that the data was invalid.

That way you are not trying to use your code to catch a data error - not something that is good to do.

You don't really need a special library to handle this, it is as much a thought exercise as anything. Actually, a "Model" handler (think MVC) would do the job nicely. Alternatively, you simply need to filter out any really bad data (zero or excessively long for example) before passing it to a parser function - if the parser fails to fully understand the data, default to returning an error message to the user.