-
-
Save pvenkatakrishnan/3e03440d8262f9f5b12e to your computer and use it in GitHub Desktop.
Error Handling event emitter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
}) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
😄