Custom rails error pages other than 404 and 500

September 18, 2008

I don't dabble with rescue_action_in_public.

Probably not that well known, but instead I like to do stuff like this:

# file: /config/initializers/rescue_responses.rb

# Raised when user tries to access page he/she has no access to
class PermissionDenied < Exception
end

ActionController::Base.rescue_responses['PermissionDenied'] = :forbidden

Basically define your own custom exceptions, and add them to the ActionController::Base.rescue_responses hash. The key must match the class name of the exception, the value should match any of the HTTP status codes defined in the ActionController::StatusCodes rails module.

Now you can raise the exception any place you like, and it will attempt to show a static error page based on the status code. So for example, because :forbidden is linked to status code 403 it would try to show /public/403.html. If that file doesn't exist it would fall back to showing /public/500.html.


Comments

  1. Exactly what I was looking for, thank you! This is also good if you are using Rails without ActiveRecord and still want to 404 (based on a service lookup or some such)... same idea, where you create your own RecordNotFound:

    class RecordNotFound < Excpetion
    end

    ActionController::Base.rescue_responses['RecordNotFound'] = :not_found

    reidmix on December 17, 2008 at 1:50 am

Leave a comment