Node.js / Express Error Reporting in 30 lines

Creating a DIY server-side 2po.st error notification service

postError.js - Send a POST request to a 2po.st link

var https = require('https');
var urlPath = //2PO.ST LINK PATH;
exports.postError = function(err) {
try {
var post_data = JSON.stringify({error: err, stack_trace: err.stack}, encoding='utf8');

var post_options = {
host: '2po.st',
port: '443',
path: urlPath,
method: 'POST',
headers: {'Content-Type': 'application/json','Content-Length': post_data.length}
};
var post_req = https.request(post_options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
(res.statusCode == 200) ? console.log('Error report sent using 2po.st')
: console.log('2po.st Response: ' + chunk);
}};
});

post_req.write(post_data); post_req.end();
} catch(err) {
console.log(err);
}
};

Add 2po.st error reporting to Express

var errorReporting = require('./postError');
//Express middleware, etc.

//Add callback to be run when an error occurs in Express, before other routes
app.use(function(err, req, res, next) {
errorReporting.postError(err);
next(err);
});

//Routes, server setup, etc.

Add 2po.st error reporting to any Node code

var errorReporting = require('./postError');

//Enclose error-prone code in try-catch block
try {
//CODE THAT COULD CAUSE AN ERROR
catch(err) {
errorReporting.postError(err);
});

Back Home