How to handle routing error in Rails 4 with alchemy cms gem?

392 Views Asked by At

So in our Rails 4.2 application, there is the alchemy_cms gem which requires its routes to be mounted last in config/routes.rb.

SampleApp::Application.routes.draw do
  #other routes for the rails app here
  # :
  # :
  mount Alchemy::Engine => '/'
end

We get routes like "/somehacker/routingurl" which then falls out to the Alchemy::Engine to handle, resulting in a default 500 error. If I wanted to do a custom 404 error, then the proper way to do it is to build a custom 404 page and have Alchemy handle the redirect? Otherwise since the Alchemy docs specify that it has to be the last route in config/routes.rb, there won't be a way to add a catchall route to redirect to some kind of error page I assume.

EDIT:

One of the problems is that there are some routes that are like the invalid "somehacker" route above that do need to be parsed by the Alchemy routing engine, such as "/en/us" where "en" is a valid locale. This is why I initially thought to put the route handling in the Alchemy engine's routes file.

1

There are 1 best solutions below

2
Praveen George On

If it is difficult for you to configure and use the Alchemy cms gem to redirect unknown routes into a custom defined page, you can use the bellow method to implement the same with a small coding tweak given bellow:

Rails 4.XXX

1. First Method.

(routes.rb)

You can still use a simple get to redirect all unknown routes.

  get '*path', to: 'home#index'

If you wish to provide routing to both POST and GET requests you can still use match, but Rails wants you to specify the request method via via.

  match "*path" => "home#index", via: [:get, :post]  

Remember that routes.rb is executed sequentially (matching the first route that fits the supplied path structure), so put wildcard catching at the bottom of your matchings.

Here you can replace the home#index with any custom path that you defined in you application, also note that it is important to keep this redirection code only at the bottom of routes.rb.

2. You can follow the bellow tutorial on the same problem in a different perspective to solve can be found.

Custom 404 error page with Rails 4