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
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 defines #run_rescue_handler
. However, with the current version 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?