tek*_*agi 3 ruby rack ruby-grape grape-api
如您所知,您可以指定路由中需要参数,如下所示:
requires :province, :type => String
但是,我希望能够更改引发的错误,并在未给出参数时提供我自己的错误JSON.
我怎么能这么容易做到?猴子补丁我很好.
编辑:我在第191行看到rescue_from,看起来它可能会有所帮助,但我不知道如何使用它.
https://codeclimate.com/github/intridea/grape/Grape::API
由于您基本上只想重新构造错误,而不是完全更改文本,因此您可以使用自定义错误格式化程序.
例:
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
Run Code Online (Sandbox Code Playgroud)
测试它:
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"}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2599 次 |
| 最近记录: |