ruby-on-rails - 发出 JSON 错误输出而不是 JSON 请求的 HTML

标签 ruby-on-rails ruby json ruby-on-rails-3 actioncontroller

我的团队正在使用构建在 collection+JSON 之上的超媒体 API使用我们修改过的 collection+JSON gem .我们希望在出现错误且请求格式为 JSON 时看到这一点:

{
   collection:
   {
      error:
      {
         'title': 'Application Error',
         'message': 'Sorry, we can't process your request at this time',
         'code': 500
      }
   }
}

取而代之的是,JSON 解析器很难处理:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>Action Controller: Exception caught</title>
  <style>
    body {
      background-color: #FAFAFA;
      color: #333;
      margin: 0px;
    }

我知道如何在 ApplicationController 中使用 Rails 的 rescue_from 来做到这一点:

class ApplicationController < ActionController::Base
  rescue_from ActionController::UnpermittedParameters, with: :bad_parameters
  rescue_from Exception, with: :exception_handling

  def bad_parameters
    respond_to do |format|
      format.html do
        if( request_is_local )
          # render helpful stack trace and stuff
        else
          render :file => 'public/404.html', :status => :not_found, :layout => false
        end
      end
      format.json { render :json => BadParametersEndpoint.new(:context => self).to_json, :status => :not_found }
    end
  end


  def exception_handling(exception)
    respond_to do |format|
      format.xml  { render :xml  => '<xml><error>Whatever</error></xml>', :status => 500 }
      format.json { render :json => ExceptionEndpoint.new(:exception => exception), :status => 500 }
      format.html do
        if( Rails.env == 'development' ) # there must be a better test ... 
                                         # somehow using config.consider_all_requests_local
          # render helpful stack trace and stuff
        else
          render :file => 'public/500.html', :status => 500, :layout => false
        end
      end
    end
  end
end

但如果我这样做,我如何保留 Rails 提供的方便的 HTML View ,或者更好的是,保留由像 better_errors 这样的 gem 提供的 HTML View ?

最佳答案

看来您还没有将 Rails 应用配置为仅限 api。

要做到这一点,您必须在 config/application.rb 文件中添加 config.api_only = true

例子:-

在config/application.rb 文件中

module CustomApi
  class Application < Rails::Application
  config.load_defaults 5.1
  config.api_only = true
  config.time_zone = 'UTC'
 end
end

关于ruby-on-rails - 发出 JSON 错误输出而不是 JSON 请求的 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23745257/

相关文章:

ruby-on-rails - 未定义方法 `status' 为 nil :nilclass

ruby - 我的 ruby 在哪里?

json - log4net.ext.json : ERROR Failed to find type [log4net. 布局.SerializedLayout,log4net.Ext.Json]

php - 加速非常慢的 PHP 脚本生成大型 JSON 数组的速度

python - 如何从 Python POST 请求中获取 JSON 数据

ruby-on-rails - Rails3 - 如何为嵌套资源制作提交按钮

ruby-on-rails - ActiveRecord::Relation 返回不同的类对象

ruby-on-rails - Sidekiq worker 正在泄漏内存

ruby - 如何将 gem 配置为只使用系统 gem?

ruby-on-rails - rails : Validate Unique Pairs