Piane_Ramso Piane_Ramso - 1 month ago 12
Node.js Question

Node.js Express app handle startup errors

I have app in Node.js and Express. I need to write tests for it. I have a problem with handling Express app errors. I found this How do I catch node.js/express server errors like EADDRINUSE?, but it doesn't work for me, I don't know why. I want to handle errors, which can occured while expressApp.listen() is executing (EADDRINUSE, EACCES etc.).

express = require('express')
listener = express()

#doesn't work for me
listener.on('uncaughtException', (err) ->
#do something
)

#doesn't work too
listener.on("error", (err) ->
#do something
)

#this works, but it caughts all errors in process, I want only in listener
process.on('uncaughtException', (err) ->
#do something
)

listener.listen(80) #for example 80 to get error


Any ideas?

Answer

First off, expressJS does not throw the uncaughtException event, process does, so it's no surprise your code doesn't work.

So use: process.on('uncaughtException',handler) instead.

Next, expressJS already provides a standard means of error handling which is to use the middleware function it provides for this purpose, as in:

app.configure(function(){
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

This function returns an error message to the client, with optional stacktrace, and is documented at connectJS errorHandler.

(Note that errorHandler is actually part of connectJS and is only exposed by expressJS.)

If the behavior the existing errorHandler provides is not sufficient for your needs, its source is located at connectJS's errorHandler middleware and can be easily modified to suit your needs.

Of course, rather than modifying this function directly, the "correct" way to do this is to create your own errorHandler, using the connectJS version as a starting point, as in:

var myErrorHandler = function(err, req, res, next){
    ...
    // note, using the typical middleware pattern, we'd call next() here, but 
    // since this handler is a "provider", i.e. it terminates the request, we 
    // do not.
};

And install it into expressJS as:

app.configure(function(){
    app.use(myErrorHandler);
});

See Just Connect it, Already for an explanation of connectJS's idea of filter and provider middleware and How To Write Middleware for Connect/Express for a well-written tutorial.

You might also find these useful:

Finally, an excellent source of information regarding testing expressJS can be found in its own tests.