bluekeys
bluekeys

Reputation: 2267

Throw an error from within a node connection and catch it in the server error handler

I would like to handle the case where I don't like the format of the incoming data by throwing a server level error.

var net = require('net');

var server = net.createServer(function(c) {
  c.on('data', function() {
    // ***THROW ERROR***
  });
});

server.on('error', function (e) {
    // ***CATCH IT****
});

server.listen(8124);

The example is a quick modification to a copy and paste from the node documentation.

I have tried throw new Error("error"); to no avail!

Upvotes: 2

Views: 92

Answers (1)

bluekeys
bluekeys

Reputation: 2267

It appears that the answer is simple.

var net = require('net');

var server = net.createServer(function(c) {
  c.on('data', function() {
    c.server.emit('error', '!!!simple!!!');
  });
});

server.on('error', function (e) {
    // ***CATCH IT****
});

server.listen(8124);

Upvotes: 2

Related Questions