虽然你的问题不是很清楚,但这是我要查看的内容......
--
错误处理
我们使用 config.exceptions_app 中间件挂钩处理自定义错误页面
我们为它编写了一个名为 exception_handler 的 gem,并且有一个流行的答案 here。还有一个great github gist here
我建议使用 exceptions_app 中间件挂钩,并附带一个控制器来捕获和响应错误:
# config/environments/development.rb
config.consider_all_requests_local = false # true -> for testing
#config/application.rb
config.exceptions_app = ->(env) { ExceptionController.action(:show).call(env) }
#app/controllers/exception_controller.rb
Class ExceptionController < ApplicationController
respond_to :js, :json, :html
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_with @rescue_response
end
end
这将允许您创建所需的自定义页面,并能够返回所需的mime 类型
--
respond_to
作为一般规则,Rails 允许您使用 respond_to 代码块向不同的 mime types 提供不同的响应
您可以通过两种方式使用该块:
#app/controllers/your_controller.rb
Class YourController < ApplicationController
def your_action
respond_to do |format|
format.json
format.html
end
end
end
或者,您可以同时使用respond_to 和respond_with 方法:
#app/controllers/your_controller.rb
Class YourController < ApplicationController
respond_to :js, :json, :html
def your_action
@your_variable = "test"
respond_with @your_variable #-> responds with appropriate mime-type
end
end
--
回复
如果你想发出一个JSON-only 响应,你需要使用上面所有的代码来创建一个允许你传递 JSON 响应的控制器。
您必须记住,JSON 响应只是数据响应的一种类型——具体来说,它只是提供您响应的所有数据的嵌套散列。
如果您想收到对错误的 JSON 响应,您基本上需要能够创建一个控制器来处理正确的 mime 类型。我上面推荐的将为您做到这一点