Search code examples
backbone.jsmarionetteairbrake

Override marionettejs render method to send airbrakes to airbrake.io


I want to send airbrakes that arise due to rendering of a marionette view to airbrake.io But i do not want to put try catch in all the methods of the view. Is there a better way to do it?

Current implementation:

try {
  ...
} catch (e) {
  Airbrake.push(error);
}

Solution

  • you should use a mixin similar to this,

    Define the mixin function

        var asAirBreakView = function () {
            //note, this function assumes it's being called using 'apply' or 'call'
            //so context could be set to view's prototype.              
    
            //store original render function
            var originalRender = this.render
    
            //replace the render function with the wrapped render function
            this.render = function () {
                try {
                    //call original render function with arguments passed in
                   return originalOnRender.apply(this, arguments);
                } catch (e) {
                    Airbrake.push(error);
                    throw e;
                }
            };
        };
    

    Apply the mixin to your view

        var view =  Marionette.ItemView.extend({  
            //define your view here
        });
    
        //Apply the mixin to prototype of your view
        view = asAirBreakView.apply(view.prototype);
    

    I really love how you can add behaviour to functions and classes in javascript. it's something you don't get in classic inheritance languages like C# or java.