Rails has the concept of Environments to represent the stages of an application’s lifecycle (test, development, and production are the defaults). Errors are handled as appropriate for the deployment target. The test and development environments provide developer-relevant error handling whereas the production environment returns an error page with HTTP status 500 (Application Error).
ActionController::Rescue is the module responsible for error handling.
It is possible to configure the error page returned by your Rails application, in either a global or controller specific way. By combining these approaches you can have a global default and override it in individual controllers.
Navigate to your apps /controller directory and edit application.rb:
def rescue_action_in_public(exception)
render :text => "<html><body><p>
There was a global error processing your request.</p>
<!-- #{exception} --></body></html>"
end
def local_request?
false
end
Edit the controller you would like to have respond to errors differently to include its own implementation of rescue_action_in_public:
def rescue_action_in_public(exception)
render :text => "<html><body>
<p>There was a controller specfic error processing your request.</p>
<!-- #{exception} --></body></html>"
end
These examples show simple text rendering for error pages, but there are many other possibilities(such as email, logging, redirects, etc.) in the rescue_action_in_public method(see HowtoSendEmailWhenRailsThrowsAnException, for example).
One of the above possibilities, rather than using text, is to render a template right in the rescue_action method, thusly:
def rescue_action_in_public(exception)
render :template => "controller/404"
end
See HandlingPreControllerErrors.
consider_all_requests_local to falseWhen working on this functionality locally you will need to make sure that your /config/environments/development.rb has the following set in it:
config.action_controller.consider_all_requests_local = false
Also, despite defining local_request? as above, you may have to change the address used to make the request. Neither localhost, not 127.0.0.1 work, instead use the actual IP address of your machine.
—-
Question: Does this mean then that there is no simple way to define the default error page for a controller, a way that works whether in development or production or trying it out on localhost?
Answer: Yes, there is. Redefine the method rescue_action in application_controller.rb and it will be executed whether its in development, production, from a remote host or a localhost. The only good reason to do this though is to check your pretty error message that you will eventually be assigning to rescue_action_in_public. While the errors normally thrown in development aren’t pretty, they’re very informative and help you locate errors in your code.
—-
Sandro Paganotti has written a small tutorial on How to create and handle Exceptions in Ruby on Rails
—-