I wrote this simple server in node. Actually my goal is to better understand exception handling best practices in Node. So my question is more specific. Is this code bullet proof to exceptions? Are all errors or exceptions propertly handled? How would you make it more safe? Where would you put try/catch? Is there a place where try/catch is missing?

var http = require('http');

// Register handler for incoming requests.
var server = http.createServer(function(request, response) {

    var body = "";


    request.on('error', function(err) {

    // Listen for incoming data in the request.
    request.on('data', function(chunk) {
        body += chunk

    // Has all data arrived?
    request.on('end', function() {

        // We should send response only when the whole request has been received, isn't it?
        response.writeHead(200, {
            'Content-Type': 'text/html',
            'X-Powered-By': 'bacon'

        response.on('error', function(err) {

        response.write('<h1>Hello, World!</h1>');



// Listen on some port

If you're going to continue using raw, low level, http then you've done good enough (although you should probably return a 500 response code back to the client). In reality though, you're unlikely to continue working with Node at such a low level. Most Node applications are going to use a framework like Express, which has the concept of Middleware. Typically, you'd use some middleware to handle runtime errors.

RisingStack has a great tutorial for creating a simple Express server with middleware error handling.

|improve this answer|||||
  • \$\begingroup\$ thanks I started with node recently and I find a bit puzzling exception handling here due to fact of having async/sync code mixed and that for example throw/cathch isn't useful with async. So I am trying to see best practice to effectively handle all exceptions \$\endgroup\$ – user126614 Feb 5 '17 at 12:08
  • 1
    \$\begingroup\$ @user200400 you're going to want to learn about Promises then. They provide a very nice async error handling abstraction. \$\endgroup\$ – RubberDuck Feb 5 '17 at 12:38
  • \$\begingroup\$ Thanks will definitely check it. But I read in docs sometimes even async function can throw exception...?! what you do in that case? \$\endgroup\$ – user126614 Feb 5 '17 at 12:53
  • \$\begingroup\$ I think maybe you're a bit too worried atm. I'd recommend just building something useful and dealing with this scenarios as they arise. \$\endgroup\$ – RubberDuck Feb 5 '17 at 12:54
  • \$\begingroup\$ final thing: does createServer throw? I couldn't find in doc \$\endgroup\$ – user126614 Feb 5 '17 at 17:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy