Search code examples
ruby-on-railsrubyexceptionairbrake

Get exception content in Rails Router


So I handle exceptions with an error controller to display dynamic content to my users in production. I have it in my route file to do:

  # Errors
  %w( 404 422 500 ).each do |code|
    get code, :to => "errors#show", :code => code
  end

The only problem is now that I'm routing on errors such as that I lose information in my controller when I want to notify Airbrake. How can I maintain the exception information and send it to Airbrake on a 500? Right now all I get is the env that was occurring at the time of the exception which is less helpful for debugging purposes.

class ErrorsController < ApplicationController

  def show
    notify_airbrake(env) 
    render status_code.to_s, :status => status_code
  end

  protected

  def status_code
    params[:code] || 500
  end

end

Solution

  • Are you handling an error by redirecting to a URL like http://your.site/500? That will be just an HTTP request like any other, losing the exception context you're after. Instead, you probably want to be using ActionController's Rescue functionality. It would look like this:

    class ApplicationController < ActionController::Base
      rescue_from StandardError, with: :render_error
    
      private
    
      def render_error(error)
        notify_airbrake(error)
        render text: 500, status: 500
      end
    end
    

    You can add multiple rescue_from declarations to handle different kinds of error, like the ActiveRecord::RecordNotFound from the Rails guide's example.