7

How to rescue from RoutingError in rails 3.1 application. If i'm nt mistaken it was possible to use rescue_from RoutingError in application controller but now it's not possible.

roman
  • 5,100
  • 14
  • 44
  • 77

3 Answers3

7

I wasn't able to replicate @matthew-savage's results. However, per the Rails guide on route globbing and this question on another StackOverflow question, I solved this issue like so:

routes.rb

match "*gibberish", :to => "home#routing_error"

notice how I included text after the wildcard. The controller is fine as shown above:

controller/home_controller.rb

....
def routing_error
    render text: "Not found, sorry", status: :not_found
end
Community
  • 1
  • 1
aboutaaron
  • 4,869
  • 3
  • 36
  • 30
7

There is no great way to handle it, but there are a few workarounds. The discussion here yields the following suggestion:

Routes

Add the following to your routes file:

match "*", :to => "home#routing_error"

and handle the error in this action:

def routing_error
  render text: "Not found, sorry", status: :not_found
end
Matthew Savage
  • 3,794
  • 10
  • 43
  • 53
gtd
  • 16,956
  • 6
  • 49
  • 65
  • The more technically correct response would be `render text: "Not found, sorry", status: :not_found, content_type: Mime::HTML` to correctly handle responses like `/icon.png` – kizzx2 Oct 13 '13 at 16:36
  • Infact, the solution from @aboutaaron worked for me. Just a "*" in the route-pattern didn't work. Needed to add some CRAP :) – Satya Kalluri Jul 17 '14 at 15:45
0

Good example.

route.rb

  • Rails 3:

    match '*unmatched_route', :to => 'application#raise_not_found!'

  • Rails 4:

    get '*unmatched_route' => 'application#raise_not_found!'

application_controller.rb

def raise_not_found!
  raise ActionController::RoutingError.new("No route matches #{params[:unmatched_route]}")
end
shilovk
  • 11,718
  • 17
  • 75
  • 74