Last active
August 29, 2015 14:02
-
-
Save bergerjac/5477725b1254a362a031 to your computer and use it in GitHub Desktop.
Node.js Express Async Error Handler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* refs | |
http://machadogj.com/2013/4/error-handling-in-nodejs.html | |
http://nodejs.org/api/process.html#process_event_uncaughtexception | |
*/ | |
function asyncTryCatch(tryFunction, catchFunction, keepAliveOnHandled) | |
{ | |
process.on('uncaughtException', function(ex) | |
{// hook onto uncaughtException -> execute catch | |
var handled = catchFunction(ex); | |
if (!handled) | |
{// NOT handled -> throw | |
throw ex; | |
process.exit(1); //? unnecessary? | |
} | |
else if (handled && !keepAliveOnHandled) | |
{// handled but NOT staying alive -> exit w/ error code | |
process.exit(1); | |
} | |
}); | |
tryFunction(); // try async code | |
} | |
asyncTryCatch( | |
function() | |
{ | |
http.listen(8080, function() | |
{ | |
log.info("listening on localhost:8080"); | |
}); | |
}, | |
function(ex) | |
{ | |
if (ex.message.indexOf('listen EADDRINUSE') > -1) | |
{// (node v0.10.28) http://nodejs.org/api/net.html#net_server_listen_port_host_backlog_callback | |
log.error("port 8080 is already bound. kill the other process first."); | |
return true; | |
} | |
else | |
{// (some other error) | |
throw ex; | |
} | |
} | |
); | |
log.info("this line is executed"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment