http://myside.com/MyControllers/213123123
给了我Couldn't find MyController with id=213123123
def show
render :text=>'testing ....'
begin
@ingredient = MyController.find(params[:id])
rescue RecordNotFound => e
puts "Test........"
end
respond_to do |format|
format.html # show.html.erb
format.json { render json: @ingredient }
end
end
渲染:text =>'测试......'如果给出无效ID ,则不会报复 无法找到id = 213123123
的MyController任何人都会指导我正确的语法
答案 0 :(得分:0)
您有几个重要的语法问题:
- 您的路线似乎格式错误(you need to use
snake_case
rather thanCamelCase
)- 您最好使用
醇>exception_app
中间件挂钩来捕获异常
我会按如下方式解决这些问题:
#config/routes.rb
resources :my_controllers #-> domain.com/my_controllers/:id
#app/controllers/my_controllers_controller.rb
Class MyController < ApplicationController
def show
@ingredient = MyController.find params[:id]
end
end
我实际上已经写了很多关于这个here&amp; written a gem here&amp;有一个很棒的github gist here
这将使您能够使用exceptions_app
中间件钩子捕获任何异常:
#config/application.rb
config.exceptions_app = ->(env) { ExceptionController.action(:show).call(env) }
这将允许您通过名为ExceptionController
的单独控制器路由任何异常:
#app/controllers/exception_controller.rb
Class ExceptionController < ApplicationController
layout 'application'
def show
@exception = env['action_dispatch.exception']
@status_code = ActionDispatch::ExceptionWrapper.new(env, @exception).status_code
@rescue_response = ActionDispatch::ExceptionWrapper.rescue_responses[@exception.class.name]
respond_to do |format|
format.html { render :show, status: @status_code, layout: !request.xhr? }
format.xml { render xml: details, root: "error", status: @status_code }
format.json { render json: {error: details}, status: @status_code }
end
end
end
#app/views/exception/show.html.erb
Put what you want here
这将帮助您捕获异常 - 如果您想在开发中进行测试,则应该执行此操作:
#config/environments/development.rb
config.consider_all_requests_local = false