Grape custom error with status code

3.4k Views Asked by At

Hi I am working on rails project right now with Grape Basically I wanna make a custom error with grape since its supported. I have managed to create the custom error, something like this

module API
  module ErrorFormatter
    def self.call(message, backtrace, options, env)
      { :response_type => 'error', :details => message }.to_json
    end
  end
end

it works fine, but What if I wanna add more details on it, like status code that we grape send/we manually pass on method error! so it would be have the status code on the json.

it could be something like this

{ :status_code: *status_code_here*, :response_type => 'error', :details => message }

How do i set the value for status_code_here

EDITED

This is in base/root for grape

  class Base < Grape::API
    format :json
    error_formatter :json, API::ErrorFormatter

    mount API::V1::Base
  end

So it means now I am using the custom error instead of the pre-defined error of grape. This custom error will be invoked in two ways as I know:

  1. Grape automatically use this when you send a missing parameter on the API that you put the parameter as requires
  2. When you explicitly call the error!() method as this https://github.com/intridea/grape#raising-exceptions

Any help?

Thanks

1

There are 1 best solutions below

0
On BEST ANSWER

The status code is embedded in the rack environment.
You can acquire it via:

env['api.endpoint'].status

So your method's body would be:

{ :status_code: env['api.endpoint'].status, :response_type => 'error', :details => message }