Manuel Jacob
Manuel Jacob

Reputation: 2014

How to remap exceptions with Grape?

In a Ruby project using Grape, I have a custom exception Api::Exceptions::InvalidValueError that subclasses Grape::Exceptions::Base. If a validation fails (which causes Grape::Exceptions::ValidationErrors to be raised), I’d like to return the same response as if Api::Exceptions::InvalidValueError was raised.

Previously, I achieved it like this:

rescue_from Grape::Exceptions::ValidationErrors do |e|
    begin
        raise Api::Exceptions::InvalidValueError, e.full_messages
    rescue Api::Exceptions::InvalidValueError => invalid_value_error
        run_rescue_handler(:error_response, invalid_value_error)
    end
end

After upgrading to Grape 2.1.3, the above code fails with “undefined method run_rescue_handler”. With old versions of Grape, it worked because the block passed to rescue_from was executed in the context of the Grape::Middleware::Error instance that has #run_rescue_handler. However, with current versions of Grape, the block is executed in the context of the API endpoint instance, so Grape::Middleware::Error#run_rescue_handler can’t be called like this.

Is there a better way to achieve the goal that works with current versions of Grape?

Upvotes: 0

Views: 51

Answers (0)

Related Questions