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: 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
def template_error(exception)
  session.delete :search
  redirect_to "/"+request.path.split('/').second, :alert => "Template error: #{exception.message}."

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.

Leave a Reply

Please log in using one of these methods to post your comment: Logo

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.