ControllerExceptions are a way of simplifying controller code by placing exceptional logic back into the MVC pattern.
When a ControllerException is raised within your application merb will attempt to re-route the request to your Exceptions controller to render the error in a friendly mannor.
For example you might have an action in your app that raises NotFound if a some resource was not available
def show product = Product.find(params[:id]) raise NotFound if product.nil? [...] end
This would halt execution of your action and re-route it over to your Exceptions controller which might look something like
class Exceptions < Application
def not_found render :layout => :none end
end
As usual the not_found action will look for a template in
app/views/exceptions/not_found.html.erb
Note: All standard ControllerExceptions have an HTTP status code associated with them which is sent to the browser when the action it is rendered.
Note: If you do not specifiy how to handle raised ControllerExceptions or an unhandlable exception occurs within your customised exception action then they will be rendered using the built-in error template in development mode this "built in" template will show stack-traces for any of the ServerError family of exceptions (you can force the stack-trace to display in production mode using the :exception_details config option in merb.yml)
Internal Exceptions
Any other rogue errors (not ControllerExceptions) that occur during the execution of you app will be converted into the ControllerException InternalServerError, and like all ControllerExceptions can be caught on your Exceptions controller.
InternalServerErrors return status 500, a common use for cusomizing this action might be to send emails to the development team, warning that their application have exploded. Mock example:
def internal_server_error MySpecialMailer.deliver( "team@cowboys.com", "Exception occured at #{Time.now}", params[:exception]) render :inline => 'Something is wrong, but the team are on it!' end
Note: The special param[:exception] is available in all Exception actions and contains the ControllerException that was raised (this is handy if you want to display the associated message or display more detailed info)
Extending ControllerExceptions
To extend the use of the ControllerExceptions one may extend any of the HTTPError classes.
As an example we can create an exception called AdminAccessRequired.
class AdminAccessRequired < Merb::ControllerExceptions::Unauthorized; end
Add the required action to our Exceptions controller
class Exceptions < Application def admin_access_required render end end
In app/views/exceptions/admin_access_required.rhtml
<h1>You're not an administrator!</h1> <p>You tried to access <%= @tried_to_access %> but that URL is restricted to administrators.</p>
| Constants | |
|---|---|
| STATUS_ |
Mapping of status code names to their numeric value. |
<code/>and<pre/>for code samples.