在Rails 3中为自定义404捕获未知操作 [英] Catch Unknown action in Rails 3 for custom 404

查看:75
本文介绍了在Rails 3中为自定义404捕获未知操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Rails 3中捕获未知操作错误,该错误在开发中显示未知操作"错误,在生产中显示404.html.我尝试将此rescue_from处理程序放在我的ApplicationController上(以及在实际的控制器上,以防万一),但是我仍然看到难看的错误.

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 handler on my ApplicationController (and also on an actual controller, just in case) but I still see the ugly error.

我在404上有自定义内容,并且不能是纯HTML文件.

I have custom stuff on the 404, and it can't be plain .html file.

我的路线:

match '/user/:id/:action', controller: 'users'

我正在访问的URL:/user/elado/xxx

The URL I'm accessing: /user/elado/xxx

rescue_from代码:

rescue_from AbstractController::ActionNotFound, :with => :action_not_found

def action_not_found
  render text: "action_not_found"
end

浏览器中的错误:

Unknown action

The action 'xxx' could not be found for UsersController

在控制台中:

Started GET "/user/elado/xxx" for 127.0.0.1 at 2011-09-07 19:16:27 -0700

AbstractController::ActionNotFound (The action 'xxx' could not be found for UsersController):

也尝试过rescue_from ActionController::UnknownAction.

有什么建议吗? 谢谢!

Any suggestions? Thanks!

推荐答案

rescue_from在Rails 3出现时被稍微破坏了(在3.1中也被破坏了).基本上,您不能:

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

rescue_from ActionController::RoutingError

了.请参见此处.

目前的解决方案是hamiltop推荐的解决方案.使用捕获到您的路由错误"路由的所有路由.确保将其放在config \ routes.rb文件的末尾,以便最后处理它.

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

注意:此方法有一个主要缺点.如果您使用Jammit或Devise之类的引擎,则catch的所有路线都会使Rails忽略引擎的路线.

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.

如果您使用的引擎不具有自己的路线,那应该没问题. 但是,如果您确实使用定义了自己路线的引擎,请参阅@arikfr的答案.

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.

这篇关于在Rails 3中为自定义404捕获未知操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆