Manual Error Redirects
Hi
First of all, thank you very much for your excellent Gem!! I appreciate that this is not really an issue with your gem but more of a use case but I am hoping you might be able to give me some advice, my app has some admin only pages on it so I want to throw a 403 error if a non admin user tries to access those pages. I have seen lots of people suggesting online to do the following:
render :file => File.join(Rails.root, 'public/403.html'), :action => 'show', :status => 403, :layout => false
This is obviously manually rendering a static file which then bypasses Gaff, is there any way throw an error myself that will be handled by Gaffe and routed to my proper error pages?
Many many thanks David
I’m not sure what your question is. If you want to know how to throw custom errors and make Gaffe handle them, the correct way to do that is to map your error class to a rescue_response (as Rails calls them) so when such an error is thrown, Gaffe handles it as a :forbidden error (ie. 403 error).
config.action_dispatch.rescue_responses.merge! 'MyCustomError' => :forbidden
Hope that answers your question!
Hi
Thanks for coming back to me so quickly!! I am trying it this way but I still can't seem to get it to work. I have added a file called custom_errors.rb into my lib folder that just has a empty method in it (possibly the problem):
`module CustomErrors
def self.throw_access_denied
end
end`
Then in my ApplicationHelper I have the following method that my code calls to check wether the user is an admin:
`include CustomErrors
def admin_only
unless user_signed_in? && current_user.is_admin?
CustomErrors::throw_access_denied
end
end`
Then finally in the application.rb I have:
config.action_dispatch.rescue_responses.merge! 'CustomErrors::throw_access_denied' => :forbidden
Should the the above, just detect that the throw_access_denied method has been called and automatically hijack it or do I need to do something specifically within the method?
Basically nothing happens, it just renders the page as normal, even if they are not allowed to so it seems like its not being hijacked.
My apologies, if I am being stupid, I really appreciate your help.
All the best David