1

I have this code somewhere in my controller:

raise PermissionDenied

When this is executed, I want to show a custom error page written in HAML, rather than the default NameError page.

Can anyone help me? Thanks.

1 Answer 1

2

The rescue_from method can be used for global exception handling.

Change theapp/controller/application_controller.rb file to add the exception handler.

class ApplicationController < ActionController::Base

  rescue_from ::PermissionDenied, :with => :render_permission_denied

  def render_permission_denied(e)
    @error = e   # Optional, accessible in the error template
    log_error(e) # Optional 
    render :template => 'error_pages/permission_denied', :status => :forbidden
  end
end

Now add a haml file called permission_denied.html.haml in app/views/error_pages directory.

%h1 Permission Denied!
  %p #{@error.message}

Refer to the rails documentation for more details.

Sign up to request clarification or add additional context in comments.

4 Comments

I get this erreur: uninitialized constant ApplicationController::PermissionDenied. Do you know what I can do?
Updated my answer. Take a look.
Did you add the change I suggested? Where have you declared the PermissionDenied class?
Oh I am so dumb xD. I hadn't declared it. Now I declared class PermissionDenied < Exception in /lib/permission_denied.rb and it works great now. Thanks +D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.