Skip to content

Instantly share code, notes, and snippets.

@dylants
Created May 21, 2014 20:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dylants/1228649e66768ccdce02 to your computer and use it in GitHub Desktop.
Save dylants/1228649e66768ccdce02 to your computer and use it in GitHub Desktop.
One way of handling errors in your main hapi app.js file. These errors would normally cause the process to stop, but we should try and stop the server prior to killing the process. Hapi by default handles errors using domains, so uncaught exceptions won't cause the server to halt.
var domain = require("domain").create();
// ...
// surround the mongo connection in a domain, to handle errors
domain.run(function() {
// connect to the database
mongoose.connect("mongodb://" + mongoConnection, function(error) {
// handle the error case
if (error) {
console.error("Failed to connect to the Mongo server!!");
console.error(error);
throw error;
}
});
});
// ...
// start the server
server.start(function() {
console.log("Server started at: " + server.info.uri);
});
// logic to handle stopping the server
function killMe(error) {
// if an error exists, log it
if (error) {
console.error(error.message);
}
if (server) {
console.log("Stopping the server...");
// try and stop the server
server.stop(function() {
console.log("Server stopped");
process.exit();
});
// just in case that doesn't work, be ready to pull the plug...
setTimeout(function() {
console.log("Timed out waiting for the server to stop, killing process (sorry)");
process.exit();
}, 30 * 1000);
} else {
// no server, just kill the process
process.exit();
}
}
// handle errors and kill requests appropriately
domain.on("error", killMe);
process.on("SIGTERM", killMe);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment