alexjfno1
alexjfno1

Reputation: 337

Catch all exceptions and display dynamic error page Ruby on Rails 4

I am currently working on a Rails 4 app and have come to the point where I want to display a custom error page to the user when any exception occurs. Currently it is using the 500.HTML in the public directory.

How can I get the app to render an erb file instead as I want to have some dynamic stuff on the page.

Thanks for you help, Alex

Upvotes: 2

Views: 2148

Answers (2)

Roman Kiselenko
Roman Kiselenko

Reputation: 44380

ApplicationController have method rescue_from rescue exceptions raised in controller actions:

in application_controller.rb:

class ApplicationController < ActionController::Base

  rescue_from YouAwesome::Exception do |exception|
    render_403(exception)
  end

  def render_403(exception)
    logger.warn("Message for log.")
    @error_message = exception.message
    respond_to do |format|
      format.html { render template: 'errors/errors', layout: false, status: 500 }
      format.all { render nothing: true, status: 500 }
    end
  end

end

Now you can create views in errors folder errors.html.erb and render @error_message variable. That it.

Upvotes: 6

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

There's an awesome tutorial by Ryan which explains exception handling in rails, have a look at this one http://railscasts.com/episodes/53-handling-exceptions

Upvotes: 2

Related Questions