Catch Unknown action in Rails 3 for custom 404

前端 未结 4 1835
挽巷
挽巷 2021-01-31 12:14

I want to catch unknown action error in Rails 3, that shows \"Unknown Action\" error on development and the 404.html on production. I tried putting this rescue_from

4条回答
  •  死守一世寂寞
    2021-01-31 12:47

    rescue_from was slightly broken when Rails 3 came out (still broken in 3.1 too). Basically you can't:

    rescue_from ActionController::RoutingError
    

    anymore. See here.

    The solution, for now, is what hamiltop recommends. Use a catch all route that goes to your "routing error" route. Make sure you put it at the end of your config\routes.rb file so it is processed last.

    # Any routes that aren't defined above here go to the 404
    match "*a", :to => "application#routing_error"
    
    def routing_error
        render "404", :status => 404
    end
    

    Note: This method has one major drawback. If you use an engine such as Jammit or Devise the catch all will route will make Rails ignore the engine's routes.

    If you aren't using an engine that has it's own routes then you should be fine. However, if you do use an engine that defines its own routes see @arikfr's answer.

提交回复
热议问题