4 thoughts on “Cannot catch listen() addressinuse error….

  1. What version of Node.js are you using? With Express 4.13.3 on Node.js 0.12.1, I found your second option worked for me.

    Simple test

    var express = require('express');
    var http = require('http');
    var app = express();
    
    http.createServer(function(req, res) {}).on('error', console.log).listen(3000);
    
    // These should all print the error object to console
    http.createServer(function(req, res) {}).on('error', console.log).listen(3000);
    http.createServer(function(req, res) {}).listen(3000).on('error', console.log);
    app.listen(3000).on('error', console.log);

    Output I get

    node test.js
    { [Error: listen EADDRINUSE] code: 'EADDRINUSE', errno: 'EADDRINUSE', syscall: 'listen' }
    { [Error: listen EADDRINUSE] code: 'EADDRINUSE', errno: 'EADDRINUSE', syscall: 'listen' }
    { [Error: listen EADDRINUSE] code: 'EADDRINUSE', errno: 'EADDRINUSE', syscall: 'listen' }
    
    
  2. The Server object is a Node.js EventEmitter. As with all EventEmitter’s, most errors are passed to the 'error' event. If no handler is registered for the 'error' event, those bubble up to be thrown. try/catch does not work because when listen is attempted, any errors that occur are caught and emitted on the 'error' event using process.nextTick() — that is, by the time the error is actually reported, the try/catch block has already exited. As a fallback, you can register an 'uncaughtException' handler on process as a catch all for any unhandled errors that occur on any EventEmitter object, but it’s best to simply set the 'error' callback on the server object. @tunniclm‘s example ought to work for you.

  3. The “proper” way to do this is:

    var express = require('express');
    var http = require('http');
    var app = express();
    var server = http.createServer(app);
    server.on('error', function (e) {
      // do your thing
    });
    server.listen(3000);

    Make the server yourself and bind the event before you start listening.

Comments are closed.