public
Last active

node.js exception handler

  • Download Gist
gistfile1.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
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;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.