【问题标题】:Rails 4 Custom Error Handling for Specific ContentTypesRails 4 针对特定内容类型的自定义错误处理
【发布时间】:2014-07-28 01:07:29
【问题描述】:

我正在使用 Rails 4 编写一个仅 API 的应用程序。

ActionController 呈现特定于某些内容类型(如 .html 和 .json)的模板

所以我的问题是,我能否返回特定于请求中发送的某些内容类型(例如 Content-Type : application/json)的自定义错误(404、500 等)?

Rails 否则会发送默认的 404.html,这不适用于期望 JSON 编码结果的客户端。

【问题讨论】:

标签: ruby-on-rails json api ruby-on-rails-4


【解决方案1】:

虽然你的问题不是很清楚,但这是我要查看的内容......

--

错误处理

我们使用 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_torespond_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 类型。我上面推荐的将为您做到这一点

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-02
    • 1970-01-01
    相关资源
    最近更新 更多