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

Neil Slater
  • 26,512
  • 6
  • 76
  • 94
tekknolagi
  • 10,663
  • 24
  • 75
  • 119
  • What do you mean by "own error JSON"? Are you wanting to change the text, or present the error in a different structure? The latter is definitely possible with a custom formatter. Could you provide example of what you currently receive for a missing param, and what you'd like to see? – Neil Slater Jul 17 '13 at 12:47
  • @NeilSlater right now it's something like `{"error": "Missing parameter name"}` but I'd like to restructure that to something like `{"response_type": "error", "response": "Missing parameter name"}` – tekknolagi Jul 17 '13 at 16:26

1 Answers1

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"}
Neil Slater
  • 26,512
  • 6
  • 76
  • 94