Basic node.js question: handling an exception

Tag: node.js Author: kmlifeng Date: 2010-09-07

Consider the following code:

var meryl = require('meryl'),
  merylex = require('meryl-extras'),
  staticfile = merylex('staticfile'),
  httpserv = require('http');

meryl.p('GET /static/<filepath>', staticfile({root: 'static', path: 'filepath'}));


This works great, until you request a file that doesn't exist. If I request /static/non-existent-file, the server crashes and says:

TypeError: undefined is not a function
    at CALL_NON_FUNCTION (native)
    at /home/user/.node_libraries/meryl-extras/lib/plugins/staticfile.js:224:9
    at [object Object]. (fs:58:5)
    at [object Object].emit (events:27:15)
    at fs:655:12
    at node.js:608:9

How can I catch this, so my app doesn't crash? Unfortunately, being such a new language, there doesn't seem to be a whole lot of examples that I've been able to find.


a solution would be to use something other than meryl, there are plenty of static file handling libraries that can cope with missing files and such.

Other Answer1

In node.js, you can catch exceptions outside a try block by listening for the uncaughtException event in the global process object. Like this:

process.on('uncaughtException', function (exception) {

This catches exceptions thrown in code not contained in a try block and also prevents your script from terminating immediately (good for running a server which usually should keep running even if unexpected problems arise).

Other Answer2

your code seems ok, but make sure you're using latest Meryl releases. Meryl is not stable yet and currently it is heavily under development. Updating Meryl will solve your issues.

Currently Meryl is v0.4.1 and Meryl Extras 0.1.4.

To update Meryl simply use npm

> npm install meryl
> npm install meryl-extras

Hope this helps.


Other Answer3

Being JavaScript it seems like you should be able to do:

try {
// do stuff
} catch (e) {
// handle exceptions

Other Answer4

I'm not sure but I think you can check that chain is not undefined before you move on.

if(chain){ //do your stuff } else { //crash }


This ended up just being a bug in meryl. :|

Other Answer5

This is a very old question, but it's getting a lot of views.

For the record, this was an actual bug in node.js. I'm sure it's fixed now. It was not possible to 'catch' this, because it wasn't a normal exception.