3

As you know, you can specify that a parameter is required in a route like so:

requires :province, :type => String

However, I would like to be able to change the error that is thrown and provide my own error JSON when the parameter is not given.

How can I do this easily? I am fine with monkey patching.

EDIT: I see at line 191 rescue_from and that looks like it could be helpful but I'm not sure how to use it. https://codeclimate.com/github/intridea/grape/Grape::API

4

1 回答 1

8

As you basically just want to re-structure the error, and not completely change the text, you can use a custom error formatter.

Example:

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

Testing it:

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"}
于 2013-07-17T20:14:54.353 回答