Skip to content

Instantly share code, notes, and snippets.

@meddulla
Created July 5, 2012 15:58
Show Gist options
  • Save meddulla/3054524 to your computer and use it in GitHub Desktop.
Save meddulla/3054524 to your computer and use it in GitHub Desktop.
node.js exception handler
process.on
(
'uncaughtException',
function (err)
{
var log = err.stack;
// print note to console
console.log("SERVER CRASHED!");
console.log(log);
// save log to timestamped logfile
var filename = "crash_" + formatDate(new Date) + ".log";
console.log("LOGGING ERROR TO "+filename);
var fs = require('fs');
fs. writeFile('logs/'+filename, log);
// email log to developer
console.log("EMAILING ERROR");
var mailer = require('./Mailer'); // this is a simple wrapper around nodemailer http://documentup.com/andris9/nodemailer/
mailer.sendMail("NODE SERVER CRASHED", log);
// If we exit straight away, the write log and send email operations wont have time to run
setTimeout
(
function()
{
// uncomment these lines to close the process instead of re-starting
//console.log("KILLING PROCESS");
//process.exit();
// re-start the server
console.log("SERVER RESTARTING...");
startServer(); // This function starts the server
},
10000
);
}
);
function pad(number, length)
{
var str = '' + number;
while(str.length < length)
{
str = '0' + str;
}
return str;
}
function formatDate(date)
{
var dateStamp = '';
dateStamp += date.getFullYear();
dateStamp += '-';
dateStamp += date.getMonth()+1;
dateStamp += '-';
dateStamp += date.getDate();
dateStamp += '_';
dateStamp += pad(date.getHours(), 2);
dateStamp += '-';
dateStamp += pad(date.getMinutes(), 2);
dateStamp += '-';
dateStamp += pad(date.getSeconds(), 2);
dateStamp += '_(';
dateStamp += date.getMilliseconds();
dateStamp += ')';
return dateStamp;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment