Search code examples
ruby-on-railscustom-error-pagesruby-on-rails-2

404 Custom Error Pages in Rails 2.3


I'm overriding render_optional_error_file to render a custom page whenever there's an error. This works great if there's an error within the application, it renders "shared/error.erb" without problem.

My application controller has a few before_filters which are responsible for setting the colour scheme of the page, defining the menu items, and authenticating users. These also run when there's an application error, which is desired.

However when a 404 page for a file is rendered, none of these filters run, so I get a black page with no menu. Is there a way I can trigger these to run? And are there any reasons why I shouldn't do this?


Solution

  • When Rails encounters a missing file, it runs render_optional_error_file(404) with status 404 on the application controller, but skips all filters, presumably since an error has already occurred.

    I added a method called run_filters to my application controller and then call that from render_optional_error_file:

    def run_filters
      #run filters or whatever
    end
    
    def render_optional_error_file(status)
      run_filters
      render "shared/error", :status => status 
    end
    

    You can also test this behaviour on your development server by including the following in your application controller:

    alias_method :rescue_action_locally, :rescue_action_in_public