Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strategies for handling exceptions between ticks (or, stacks) in Node.js? [duplicate]

I've got the following:

var  http = require('http');

server = http.createServer(function(request, response) { 
  try {
    // Register a callback: this happens on a new stack on some later tick
    request.on('end', function() {
      throw new Error; // Not caught
    })

    throw new Error; // Caught below
  }
  catch (e) {
    // Handle logic
  }
}

Now, the first Error gets caught in the try...catch, but the second Error does not appear to be getting caught.

A couple questions:

  • Does the second Error not get caught because it occurs on a different stack? If so, am I to understand that try...catch behavior is not lexically bound, but depends instead on the current stack? Am I interpreting this correctly?
  • Are there any well-explored patterns to handle this type of problem?
like image 586
Dmitry Minkovsky Avatar asked Mar 23 '23 00:03

Dmitry Minkovsky


1 Answers

You could also use a simple EventEmitter to handle an error in a case like this.

var http = require('http');
var EventEmitter = require("events").EventEmitter; 

server = http.createServer(function(request, response) { 
    var errorHandler = new EventEmitter;
    // Register a callback: this happens on a new stack on some later tick
    request.on('end', function() {
      if(someCondition) {
        errorHandler.emit("error", new Error("Something went terribly wrong"));
      }
    });

    errorHandler.on("error", function(err) {
      // tell me what the trouble is....
    });
});
like image 138
Morgan ARR Allen Avatar answered Mar 25 '23 14:03

Morgan ARR Allen