Sean Xiao
Sean Xiao

Reputation: 616

Rails 3.0.15 Custom 404 and 500

I've seen many questions about custom error views for Rails, but haven't found a solution for my problem yet!

For 404, right now my routes.rb has a catch-all at the bottom to redirect unknown named routes e.g. "webroot/adsfsdfasdf/", but it fails for invalid id e.g "webroot/people/x1df1231" - ActiveRecord::RecordNotFound (Couldn't find Person with ID=x1df1231)

For 500, I haven't found a solution yet.

I can't upgrade Rails at the moment,

Upvotes: 0

Views: 172

Answers (2)

Aaron Perley
Aaron Perley

Reputation: 629

If you want to do this in production using either or apache or nginx, you can set it in the server configuration file, not in rails.

Upvotes: 1

Sean Xiao
Sean Xiao

Reputation: 616

The best solution I have found is to use "around_filter"

on top of application_controller:

around_filter :handle_errors

and then below

def handle_errors
    yield
    rescue => e
        logger.debug "\n ====== ERROR ====== \n\n #{e.message} \n\n #{e.annoted_source_code} \n\n #{e.backtrace} \n\n ================= \n\n"
        if e.is_a?(ActiveRecord::RecordNotFound)
            render '/errors/e404'
        else
            render '/errors/e500'
        end
end

Where '/errors/e404' is a template e.g views/errors/e404.html.haml No modification to routes.rb. The original catch-all route sometimes breaks the application.

Upvotes: 0

Related Questions