34

This is my code.

if !module.parent
    try
        hons_server.listen config.port
        console.log 'Listening to port ' + config.port
    catch err
        console.error "Couldn't start server: #{String(err)}".red

hons_server is an express.js server. I'm having a hard time understanding why errors thrown as a result of hons_server.listen() aren't caught by the try/catch. When I run my server twice I get the output:

$ coffee src/server.coffee
Listening to port 9090

node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
Error: listen EADDRINUSE
    at errnoException (net.js:632:11)
    at Array.0 (net.js:733:26)
    at EventEmitter._tickCallback (node.js:192:40)

I'd like to know why the thrown error isn't caught, and how/where I can catch the EADDRINUSE error.

Hubro
  • 56,214
  • 69
  • 228
  • 381

2 Answers2

28

The accepted solution did not work for me on nodejs 0.8.22 and express 3.1.0.

This did the trick:

process.on('uncaughtException', function(err) {
    if(err.errno === 'EADDRINUSE')
         console.log(...);
    else
         console.log(err);
    process.exit(1);
});     

Also see Node.js Express app handle startup errors

Community
  • 1
  • 1
mistaecko
  • 2,675
  • 1
  • 20
  • 18
  • On express 4.17, I had to use `err.code` instead of `err.errno`. `errno` was `-98` and `err.code` was `EADDRINUSE` – ffigari Dec 31 '22 at 01:33
23

Listen for the error event on the server isntance

hons_server.on 'error', (err) ->
    console.log 'there was an error:', err.message
fent
  • 17,861
  • 15
  • 87
  • 91
  • 1
    Out of curiosity, how did you know that? I know it wasn't in [the documentation](http://expressjs.com/guide.html) and I can't find anything on which events the express server supports – Hubro Mar 03 '12 at 10:02
  • 4
    Basically, the express server is the [http Server](http://nodejs.org/docs/latest/api/http.html#http_class_http_server), which is an event emitter. – Linus Thiel Mar 03 '12 at 10:43
  • Does this still work in the newest version of Node? Please check out the answer below and update yours if needed. – Hubro May 13 '13 at 13:28
  • It still works. from express 3.0.0 and onwards, the express object no longer inherits from `http.Server`, it's just a function that gets plugged into a server. The `error` event would have to be listened on from the server object, not the express function. – fent May 13 '13 at 16:34
  • I expected the express `server.listen(function(err){...}` callback to support checking for errors, but this suggestion to listen for events like `server.on('error', function(err){...})` work very well – Nate Anderson Dec 14 '18 at 18:52
  • It works on vscode console, but in Windows cmd not, why is it? – Agustín Clemente Jan 25 '19 at 12:32