Ben
Ben

Reputation: 1368

Handling Unknown action in Rails 3

I'm new to Rails development and I have a question about handling an unknown action. What is the best way to handle that kind error?

Upvotes: 8

Views: 1974

Answers (5)

d11wtq
d11wtq

Reputation: 35318

In config/environments/development.rb, turn off consider_all_requests_local and restart the server. Now you'll see the error pages. Once you've finished designing them, turn consider_all_requests_local back on and restart the server again.

In production, people will get the 404 page you have designed. In development you see the stack trace so that you can debug your own mistakes.

Upvotes: 1

Arun Kumar Arjunan
Arun Kumar Arjunan

Reputation: 6857

In the production mode the exception will be handled automatically. But there are cases where we want to handle the exceptions. In our case we render a special layout for such pages.

In application controller you have to rescue the exceptions like this:

  PAGE_NOT_FOUND_ERRORS = ActiveRecord::RecordNotFound, ActionController::RoutingError, ActionController::UnknownAction, ActionController::UnknownController
  def rescue_action_in_public(exception)
    case exception
    when *PAGE_NOT_FOUND_ERRORS
      render_404
    else
      render_500
    end
  end


  def render_404
    render :file => File.join(RAILS_ROOT, 'public', '404.html'), :status => 404, :layout => true
  end



  def render_500
    render :file => File.join(RAILS_ROOT, 'public', '500.html'), :status => 500
  end

Upvotes: 0

ayckoster
ayckoster

Reputation: 6847

Do not handle it. If a user enters a wrong URL he will get a 404 error when you switch to production environment.

You get the exceptions only because you are in development environment.

Upvotes: 10

Michael Wales
Michael Wales

Reputation: 10628

Show a 404 error, the user has entered a URL in which you don't have a corresponding Action within the Controller (or a route) defined to handle. It should be treated the same as if the user entered example.com/controller/jbsandfodsafoiuaudsfbsadf87basdfgsadfdsa.

Upvotes: 1

skattyadz
skattyadz

Reputation: 330

You should be fine to use the default Rails handling which will load the 404 file in your public directory.

Upvotes: 0

Related Questions