Basic node.js question: handling an exception

Problem

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'}));

httpserv.createServer(meryl.cgi()).listen(3000);

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

/home/user/.node_libraries/meryl-extras/lib/plugins/staticfile.js:224
chain();
^
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.

Thanks.

Problem courtesy of: Sam

Solution

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.

Solution courtesy of: Sam

View additional discussion.

Show your support

Clapping shows how much you appreciated Jamie Munro’s story.