views:

21

answers:

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  A: 

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.

KandadaBoggu
I get this erreur: uninitialized constant ApplicationController::PermissionDenied. Do you know what I can do?
Time Machine
Updated my answer. Take a look.
KandadaBoggu
That's funny: `uninitialized constant PermissionDenied` (A)
Time Machine
Did you add the change I suggested? Where have you declared the `PermissionDenied` class?
KandadaBoggu
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
Time Machine