Nodejs error handling with domains and socket.io

I'm just starting to use domains in nodejs for error management.

There is something I cannot understand when I use them with socket.io.

What is my sample code:

io.sockets.on('connection', function cb1(socket){ socket.on('event', function cb2(data){ }); }); 

I started putting all my code in the run method

 domain.run(function(){ io.sockets.on('connection', function cb1(socket){ socket.on('event', function cb2(data){ }); }); }); 

But if an error occurred in cb1 or cb2, it is not processed!

Then I used methone binding on che cb1

 domain.run(function(){ io.sockets.on('connection', domain.bind(function cb1(socket){ socket.on('event', function cb2(data){ }); })); }); 

But if an error occurred in cb2, it is not processed!

My question is: do I need to put one “binding” on each callback? On the server and in the necessary files?

When I started to study domains, all the tutorials define them as the best solution to handle your errors at one point!

Did I miss something?

+7
source share
4 answers

If you create a socket in a domain area, then all events in this socket object that cause an error will be caught by the domain.

 domain.run(function(){ var io = require('socket.io').listen(80); io.sockets.on('connection', function cb1(socket){ socket.on('event', function cb2(data){ }); })); }); 

Try it.

0
source

(I'm dorexx45, I forgot the password)

I tried, but it partially works.

If I create an object (mysql connection) inside the domain, errors on this object are not processed!

 domain.run(function(){ var pool = mysql.createPool(); var io = require('socket.io').listen(80); io.sockets.on('connection', function cb1(socket){ socket.on('event', function cb2(data){ pool.something(); }); })); }); 

If something happens in pool.something() , for example, the syntax of a bad request or incorrect connection data, the error did not "catch" on domain.run !

0
source

Change Yes, you have to bind every callback.

Look at this screencast, it explains this problem: Node Tuts Episode VIII - Error Handling Using Domains (he starts talking about it at 13:45).

If I understood this correctly, if you are not emitting or throwing errors inside callbacks, you need to explicitly bind them using .bind or .intercept . But in my own experience in callbacks this is not enough, and I have to bind each callback to a domain.

0
source

I create a new domain for each socket:

 var Domain = require('domain'); ... io.sockets.on('connection', function (socket){ d = domain.create(); d.add(socket); d.on('error', function () { // You have access to the socket too in here, useful }); socket.on('event', function (data){ socket.on('event2', function (data){ throw new Error('I will be caught!'); }); }); }); 

Why does it work?

Domain.prototype.add will add an existing event emitter to the domain. The value of all new callbacks from events on this emitter will be implicitly bound to the domain.

0
source

All Articles