Question

I am working on a Rails app. In my app, if I enter a custom route manually in the address bar/ as URL which is not present in config/routes.rb, it will show up the below given error message.

Routing Error

No route matches "/clientImage/blablahblah"

I want this to be redirected to a proper display for all the wrong routes given by the user either intentionally/unintentionally. Any help would be greatly appreciated.

Was it helpful?

Solution

When someone enters unsupported url Rails will raise ActionController::RoutingError. You can rescue this error and render 404 Not Found html.

Rails provides some special function called rescue_from for this purpose.

class ApplicationController < ActionController::Base
   rescue_from ActionController::RoutingError, :with => :render_not_found
   rescue_from StandardError, :with => :render_server_error

   protected
     def render_not_found
        render "shared/404", :status => 404
     end

     def render_server_error
        render "shared/500", :status => 500
     end
end

Put your 404.html, 500.html in app/views/shared

OTHER TIPS

Yourapp::Application.routes.draw do
  #Last route in routes.rb
  match '*a', :to => 'errors#routing'
end

The "a" is actually a parameter in the Rails 3 Route Globbing technique. For example, if your url was /this-url-does-not-exist, then params[:a] equals "/this-url-does-not-exist". So be as creative as you'd like handling that rogue route.

In app/controllers/errors_controller.rb

 class ErrorsController < ApplicationController
      def routing
       render :file => "#{Rails.root}/public/404.html", :status => 404, :layout => false
      end
    end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top