Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Node.js crashes on TypeError even while catching uncaught exceptions

Node.js crashes on TypeError even while catching uncaught exceptions

Problem

I've noticed Node.js crashes on Type Errors even if your catching uncaught exceptions, here's some example code:

var http = require('http');

process.on('uncaughtException', function (err) {
  console.log(err.stack);
});

var test = [];

// This causes the error because test[0] is undefined
console.log(test[0].toLowerCase());

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, "127.0.0.1");

Is there any way to catch the error and keep node.js running.

Update: I should mention that the uncaughtException handler is firing in this case but it still crashes after it.

Problem courtesy of: Sean Bannister

Solution

The exception itself is not closing your program, node is stopping because there is nothing left in the event queue.

An exception still stops execution of the current function/context, so it is never getting to your http.createServer. If you move your error to just beyond the http command, it will work as expected. :)

Solution courtesy of: Dominic Barnes

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Node.js crashes on TypeError even while catching uncaught exceptions

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×