Exception handling strategies between ticks (or stacks) in Node.js?

I have 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 into try...catch , but the second Error doesn't seem to fall.

A few questions:

  • Can't catch the second Error , because it happens on a different stack? If so, should I understand that the behavior of try...catch not lexically related, but depends on the current stack? Am I interpreting this correctly?
  • Are there any well-studied patterns to solve this problem?
+4
source share
3 answers

You can also use a simple EventEmitter to handle the error in this case.

 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.... }); }); 
+3
source

The second mistake never rushes and is not caught. You add an error before adding an anonymous function as a request end event handler.

Even if you did, they won’t catch him, because he really is on another stack. You must raise an error event if you want to work this way, or simply pass the error as the first callback parameter to any callback function. (These are general agreements, not mandates.)

+2
source

catch Catch errors that occur while executing the contents of a try block. Your 'end' handler is created and assigned inside the try block, but it obviously does not execute there. It is fired when request fires the end event, and the try block has long been forgotten.

Usually you want to catch errors in the event handler and prevent them from leaking through the stack. You will never / rarely want to leave them.

As a last resort, you can register a handler for 'uncaughtException' on a process that will catch all exceptions that don't go elsewhere. But this is rarely the right decision. http://nodejs.org/api/process.html#process_event_uncaughtexception

+2
source

Source: https://habr.com/ru/post/1493751/


All Articles