x
63974806467 35963066f35b848753d8 512

Debugging RJS and Airbrake Integration

almost 7 years ago by Flavia

Popup

Rails offers a neat way of adding ajax calls to HTML elements such as links or forms. All you need to do is add remote: true as option to the link_to or form helpers. This will create a request with js format to the server. Usually, the controller responds to this request by rendering its corresponding javascript view (e.g., index.js.erb). The js view, also known as rjs, contains javascript code, which changes the DOM according to the specific request. It is a very elegant solution and the cumbersome written from scratch ajax calls are avoided. However, there is one problem with this. The javascript errors in the rjs files will not show up in the javascript console, thus making it hard to debug. The impression is that everything went well, the response from the server is 200 OK, but the javascript code does not get executed. An old RailsCast describes ways of debugging rjs: 44 Debugging RJS.

The easy solution is to simply wrap all rjs views in a try/catch block to rescue and display the errors. In this blog post we present a very elegant solution to keep the code clean and DRY and also use Airbrake for error notification.

We define a new layout called application.js.erb. This layout will be used by Rails automatically for the rjs views. Thus, we can wrap the yield in a try/catch block, keeping the rjs files readable and uncluttered:


try {
  <%= yield %>
}
catch(e) {
  alert(e.toString());
}

The next step is to integrate Airbrake as notifier. First, we must add the following line at the top of our javascript includes in application.html.erb:

<%= airbrake_javascript_notifier %>

Then, going back to our new layout, we change it such that it issues a notification when an error is raised in production.


try {
  <%= yield %>
}
catch(e) {
  <% if Rails.env == "production" %>
    function issue_notification() {
      window.Airbrake.notify({ 
        url: "<%= escape_javascript request.url %>", 
        component: "<%= params[:controller] %>", 
        action: "<%= params[:action] %>", 
        message: e.toString() });
    }
    
    $("document").ready(function() {
      setTimeout("issue_notification();", 1000);
    });
  <% else%>
    alert(e.toString());
  <% end %>
}

In our case, some of the requests did not go through to Airbrake, but found out that adding a timeout fixes this. We don’t know a specific reason for this, so we’ll get back as soon as we find more details.

All in all, these 16 lines of code make life much easier for developers debugging rjs views.

Take Off Labs wishes you all the best for 2012!

Did you like this post? Share it with your friends!