Optional catch in JavaScript

One of the things that’s been annoying me about JavaScript recently is the inability to only catch certain classes of exception, as in Java or Python, for instance. The try {..} catch(e) {..} block has always seemed too inclusive. But recently Ash found a crazy syntax in SpiderMonkey that lets us only catch certain exceptions.

try {
  // something that can throw
} catch(e if e.bar == 'foo') {
  // an error is only caught here if it has a 'bar' property of 'foo'
} catch(e if e.bar == 'baz') {
  // there can be different catches for different conditions
} catch (e) {
  // otherwise it's caught here. Without this block, the error would fall
  // through the 'try' and be re-thrown.

I haven’t bothered testing this in Internet Explorer (or any other web browser for that matter), because I’m only interested in server-side JavaScript execution at the moment. It works in at least recent SpiderMonkey CVS and Rhino 1.6r6, not sure about earlier versions.

Server-side JavaScript under Apache

Ash Berlin and I recently hacked together an Apache module that embeds the SpiderMonkey JavaScript engine and lets you run JavaScript code on the server as CGI scripts. We called it mod_js.

It was written as a proof-of-concept module at the last Fotango hack-day – Ash and I used my ancient mod_tt as a starting point and had a module capable of printing to the client in about 4 hours of work. Not bad. See the mod_js project page for the source code, examples and build instructions, if you want to have a look yourself.

Right now in mod_js you can print output to the client, and access CGI parameters in the incoming request. There’s no filesystem access or database access. This leads me to a dilemma. I feel there’s use in a stand-alone server-side JavaScript programming environment, but heavier ones than this exist already. Faced with having to re-implement the entirety of the Perl DBI layer, TCP/IP networking, disk access, etc, etc, with all the associated security problems that will happen, I’m forced to consider mod_js somewhat of a dead-end. It would probably be much more useful implemented as a mod_perl module using the Perl SpiderMonkey bindings to embed JavaScript, so I could use all the existing Perl infrastructure to support my scripts. It would be heavier, but there will be more hosting companies offering mod_perl than are willing to compile new Apache modules, or it could be run as a stand-alone daemon more easily than something written in C.

Given all of this, mod_js is still a nice proof-of-concept, though, and could be turned into a real server-side programming language. I also quite enjoy working in C every so often. It reminds me why I don’t do itmore.

Update: Ash gave it a real web page. Crazy.