How do I catch node.js/express server errors like EADDRINUSE?
17,747
Solution 1
Listen for the error
event on the server isntance
hons_server.on 'error', (err) ->
console.log 'there was an error:', err.message
Solution 2
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
Comments
-
Hubro almost 2 years
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 ofhons_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 about 12 yearsOut of curiosity, how did you know that? I know it wasn't in the documentation and I can't find anything on which events the express server supports
-
Linus Thiel about 12 yearsBasically, the express server is the http Server, which is an event emitter.
-
Hubro almost 11 yearsDoes this still work in the newest version of Node? Please check out the answer below and update yours if needed.
-
fent almost 11 yearsIt 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. Theerror
event would have to be listened on from the server object, not the express function. -
The Red Pea over 5 yearsI expected the express
server.listen(function(err){...}
callback to support checking for errors, but this suggestion to listen for events likeserver.on('error', function(err){...})
work very well -
Agustín Clemente over 5 yearsIt works on vscode console, but in Windows cmd not, why is it?