Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I catch node.js/express server errors like EADDRINUSE?

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.

like image 403
Hubro Avatar asked Mar 03 '12 07:03

Hubro


People also ask

What is Express Server in node JS?

Express Overview Express is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications. It facilitates the rapid development of Node based Web applications.


2 Answers

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

like image 63
mistaecko Avatar answered Oct 05 '22 20:10

mistaecko


Listen for the error event on the server isntance

hons_server.on 'error', (err) ->
    console.log 'there was an error:', err.message
like image 23
fent Avatar answered Oct 05 '22 18:10

fent