Skip to content

Instantly share code, notes, and snippets.

@pvenkatakrishnan
Last active December 30, 2015 10:39
Show Gist options
  • Save pvenkatakrishnan/3e03440d8262f9f5b12e to your computer and use it in GitHub Desktop.
Save pvenkatakrishnan/3e03440d8262f9f5b12e to your computer and use it in GitHub Desktop.
Error Handling event emitter
// in kraken-js/lib/util/errorUtil.js
var EventEmitter = require('events').EventEmitter;
function ErrorEmitter() {
//anything to be sent custom by kraken (if we need to) with errors
this.internalData = {
from : "kraken"
};
}
ErrorEmitter.prototype.__proto__ = EventEmitter.prototype;
ErrorEmitter.prototype = {
//ANY FANCY SUPPORT
//Eg: Check for something specific in error before emitting
emitByType: function(error) {
error.additionalInfo = this.internalData;
this.emit((error.type || 'error'), error);
}
};
module.exports = ErrorEmitter;
/**************************************************/
//request should have an error Handler attached to it before it reaches the controller logic in the app.
//still investigating which part of kraken this would go into.
var ErrorEmitter = require('./errorUtil');
req.errorEmitter = new ErrorEmitter(); // this should be done way before the controllers in the app are hit.
/**************************************************/
//when a serverError happens instead of doing the rendering template with error like today,
//we can emit an event to the app
//this goes into kraken-js/lib/error.js
exports.serverError = function () {
return function(err, req, res, next) {
//req.errorHandler should already have been there
//when the request got handed over to the app
if(req.errorHandler) {
req.errorHandler.emitByType(err);
}
//we would still need to pass err so that
//app does not continue doing the things it would normally do
//like no error happened.
next(err);
}
}
/**************************************************/
//on the app side when it gets called into controller logic
//req has errorHandler
//eg
server.get('/the/route', function(req, res) {
req.errorHandler.on('specificType', function(data) {
//specific type error handling
};
req.errorHandler.on('error', function(data) {
//generic error handling
})
});
@totherik
Copy link

totherik commented Dec 6, 2013

  1. It may be helpful to mark this as a js file
  2. express is an eventemitter, fyi

😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment