我正在使用Ruby 2.0和Rails 4.0构建Ruby on Rails api.我的应用程序几乎只是一个JSON API,所以如果发生错误(500,404),我想捕获该错误并返回格式良好的JSON错误消息.
我试过这个并且还:
rescue_from ActionController::RoutingError, :with => :error_render_method
def error_render_method
puts "HANDLING ERROR"
render :json => { :errors => "Method not found." }, :status => :not_found
true
end
Run Code Online (Sandbox Code Playgroud)
在我的ApplicationController中.
这些都没有做到这一点(根本没有捕获例外).我的谷歌搜索显示这在3.1,3.2之间发生了很大变化,我找不到任何关于如何在Rails 4.0中做到这一点的好文档.
有人知道吗?
编辑 这是我进入404页面时的堆栈跟踪:
Started GET "/testing" for 127.0.0.1 at 2013-08-21 09:50:42 -0400
ActionController::RoutingError (No route matches [GET] "/testing"):
actionpack (4.0.0) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'
actionpack (4.0.0) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
railties (4.0.0) lib/rails/rack/logger.rb:38:in `call_app'
railties (4.0.0) lib/rails/rack/logger.rb:21:in `block in call'
activesupport (4.0.0) lib/active_support/tagged_logging.rb:67:in `block in tagged' …Run Code Online (Sandbox Code Playgroud) 我正试图拯救ActionController::RoutingError,我无法让它发挥作用.我尝试了几乎所有我能在网上找到的东西,包括Rails 4中的rescue_from ActionController :: RoutingError.我有错误控制器和错误页面.我开始工作康康舞access denied和RecordNotFound,但我可以解决RoutingError.
对于康康舞我在里面使用它 application_controller.rb
rescue_from CanCan::AccessDenied do
render template: 'errors/error_403', status: 403
end
Run Code Online (Sandbox Code Playgroud)
我的路线中有这个:
match "/404", to: "errors#error_404", via: :all
Run Code Online (Sandbox Code Playgroud)
如果我做同样的事情RoutingError它将无法正常工作.
我也试过,match '*path', :to => "errors#error_404"但我得到了错误.
我怎么解决这个问题?
编辑:如果我RoutingError对拒绝访问做同样的事情:
rescue_from ActionController::RoutingError do
render template: 'errors/error_404', status: 404
end
Run Code Online (Sandbox Code Playgroud)
它不会起作用.