Nick Vanderbilt
Nick Vanderbilt

Reputation: 38450

What all exceptions map to 404.html and what exceptions map to 500.html

I am using rails3 and am looking for the list of all exceptions that would show 404.html and the list of exceptions that would map to 500.html in PRODUCTION mode.

Right now I need to add something like

rescue_from ActiveRecord::RecordNotFound, :with => :render_404

in my application_controller and I don't like it. I think Rails should handle it automatically.

Upvotes: 2

Views: 743

Answers (2)

pulcetto
pulcetto

Reputation: 21

I'm doing this in my application controller:

rescue_from Exception, :with => :handle_error

def handle_error(exception)
  if exceptions_to_treat_as_404.include?(exception.class)
    render_404
  else
    raise exception if Rails.env == 'development'
    body = exception_error_message(exception)

    #to logger
    logger.fatal( body )

    #to email
    from = '<[email protected]>'
    recipients = "<[email protected]>"
    subject = "[ERROR] (#{exception.class}) #{exception.message.inspect}"
    GenericEmail.create(:subject => subject, :from => from, :recipients => recipients, :body => body)

    #to PageRequest table
    log_request(true)

    #render error message
    render_500
  end
end


def exceptions_to_treat_as_404
  exceptions = [AbstractController::ActionNotFound,
      ActiveRecord::RecordNotFound,
                ActionController::UnknownController,
                URI::InvalidURIError,
                ActionController::UnknownAction]
  exceptions << ActionController::RoutingError if ActionController.const_defined?(:RoutingError)
  exceptions
end

Upvotes: 2

Dylan Markow
Dylan Markow

Reputation: 124419

Rails will show the 404 error whenever it can't properly map the requested URL to a controller/action (i.e. the path doesn't match any of your routes). Any other unhandled exception will show the 500 error instead.

Upvotes: 0

Related Questions