Redirecting exception to controller’s index page

I want to improve my appliations error handling by capturing common errors and just redirecting to the index page for th particular controller with a flash message.

Most suggestions I have come across suggest url_for or redirect_to but specify either root_url or a specific controller (usually post!), but redirecting to the root_url can be very confusing when you’re working with 15 models.

As ever, the Stack comes to the rescue: http://stackoverflow.com/questions/9912678/rails-how-to-request-url-except-url-params provides enough of a hint as how to proceed. The error in the logs caused by the first suggestion gave enough of a clue for a workable solution.

In app/controllers/application_controller.erb

ActionView::Template::Error, with: :template_error
...
protected
def template_error(exception)
  session.delete :search
  redirect_to "/"+request.path.split('/').second, :alert => "Template error: #{exception.message}."
end

I could possibly even write my own helper to tidy this up a bit more. I suspect there are tidier ways of working this if I give a little more thought but at least I have something that works for now.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s