Oliver Joa
Oliver Joa

Reputation: 51

How to catch error when connecting a unix-socket in node.js

the following code does not work:

#!/usr/local/opt/node-0.10.24/bin/node

var net = require('net');

try {
  socket = net.connect("/tmp/test",function () {
    socket.on('error', function(err) {
      console.log("err");
    });
  });
} catch(err) {
  console.log("err");
}

If there is a error, how can i catch it? In this example I get an: ENOENT or ECONNREFUSED (mkfifo /tmp/test). Shouldn't it print "err"?

Upvotes: 1

Views: 2532

Answers (1)

mscdex
mscdex

Reputation: 106746

You're not adding your error handler soon enough. You can also get rid of the try-catch:

var socket = net.connect("/tmp/test", function() {
  // connected
});
socket.on('error', function(err) {
  console.log("Error: " + err);
});

Upvotes: 2

Related Questions