在Rails中使用PARAMS时出现打印错误

时间:2015-05-28 07:14:19

标签: ruby-on-rails curl

对于我在RAILS中的API,我编写了一个基本上执行以下操作的代码。

class Api::V1::NameController < ApplicationController
    skip_before_filter :verify_authenticity_token

    def index

    end

    def create
          # Loading data
            data_1_W = params[:data1]
            data_2_W = params[:data2]

       while len > i
          # -Here I do some calculations with data_1_W and data_2_W. 
          # Its not important to show the code here
       end

          # -Organizing outputs to obtain only one JSON-
          # Its not important to show the code here

          # Finally HTTP responses    
          if check_error == 1
            render status: 200, json: {
            message: "Succesful data calculation",
            data_output: response_hash
            }.to_json 
          end  

    end
end 

要测试一切正常,我使用cURL命令。我注意到加载数据可能是个问题,因此代码会中断。

我想告诉用户由于某种原因加载数据是错误的(HTTP响应),但我不知道在哪里放置它。如果我将else置于我的成功状态之下,则不会打印它,因为代码只是刚刚启动(而不是在cURL中发送数据的正确名称- d '@data.json'我发送-d '@dat.json')。

我加载的数据是JSON数据{"data1":[{"name1":"value1"},{"name2":number2}...],"data2":[{"name1":"value1"},{"name2":number2...}]}。 (如果我们将其视为一个表格,此数据有70080行,其中包含2列,我在我的CODE中将其分为两个用于计算目的data_1_Wdata_2_W

有人可以帮我把它放在哪里吗?或多或少是这样的:

render status: 500, json: {
            message: "Error loading the data",
            }.to_json

2 个答案:

答案 0 :(得分:1)

将它放在引发错误的代码周围的救援块中。

E.g。

def func
  # code that raises exception
rescue SomeException => e
   # render 422 
end

答案 1 :(得分:1)

由于您在Rails工作,我建议采用rails方式。这意味着我将创建某种服务并在create action中初始化它。

现在,在服务中你可以做所有你那些时髦的东西(这也允许你清理这个控制器,让我看起来更漂亮),并且在该服务中没有满足条件的那一刻返回false。所以......

# controllers/api/v1/name_controller.rb
...
def create
   meaningful_variable_name = YourFunkyService.new(args)
   if meaningful_variable_name.perform # since you are in create then I assume you're creating some kind of resource
      #do something
   else
      render json: {
        error: "Your error",
        status: error_code, # I don't think you want to return 500. Since you're the one handling it
      }
   end
end

# services/api/v1/your_funky_service.rb
class Api::V1::YourFunkyService
   def initiliaze(params)
     @params = params
   end

   def perfom #call it save if you wish
      ....
      return false if check_error == 1 
   end
end