【问题标题】:Grape API modify parameter presence error葡萄 API 修改参数存在错误
【发布时间】:2013-07-15 15:48:23
【问题描述】:

如您所知,您可以像这样指定路由中需要的参数:

requires :province, :type => String

但是,我希望能够更改引发的错误并在未给出参数时提供我自己的错误 JSON。

我怎样才能轻松做到这一点?我对猴子补丁很好。

编辑:我在第 191 行看到rescue_from,看起来它可能会有所帮助,但我不知道如何使用它。 https://codeclimate.com/github/intridea/grape/Grape::API

【问题讨论】:

  • “自己的错误 JSON”是什么意思?您是要更改文本,还是要以不同的结构呈现错误?后者绝对可以使用自定义格式化程序。您能否举例说明您目前因缺少参数而收到的内容以及您希望看到的内容?
  • @NeilSlater 现在类似于 {"error": "Missing parameter name"} 但我想将其重组为 {"response_type": "error", "response": "Missing parameter name"}

标签: ruby rack grape grape-api


【解决方案1】:

由于您基本上只是想重新构建错误结构,而不是完全更改文本,因此您可以使用自定义错误格式化程序。

例子:

require "grape"
require "json"

module MyErrorFormatter
  def self.call message, backtrace, options, env
      { :response_type => 'error', :response => message }.to_json
  end
end

class MyApp < Grape::API
  prefix      'api'
  version     'v1'
  format      :json

  error_formatter :json, MyErrorFormatter

  resource :thing do
    params do
      requires :province, :type => String
    end
    get do
      { :your_province => params[:province] }
    end
  end
end

测试它:

curl http://127.0.0.1:8090/api/v1/thing?province=Cornwall
{"your_province":"Cornwall"}

curl http://127.0.0.1:8090/api/v1/thing
{"response_type":"error","response":"missing parameter: province"}

【讨论】:

    猜你喜欢
    • 2015-06-13
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    • 2013-11-30
    • 1970-01-01
    • 2014-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多