Handling Unknown action in Rails 3
I'm new to Rails development and I have a ques开发者_开发问答tion about handling an unknown action. What is the best way to handle that kind error?
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.
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
.
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.
You should be fine to use the default Rails handling which will load the 404 file in your public directory.
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
精彩评论