Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a catch when running handler #2483

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion lib/grape/middleware/error.rb
Original file line number Diff line number Diff line change
Expand Up @@ -116,16 +116,19 @@ def run_rescue_handler(handler, error, endpoint)
handler = public_method(handler)
end

handler_exception = nil
response = catch(:error) do
handler.arity.zero? ? endpoint.instance_exec(&handler) : endpoint.instance_exec(error, &handler)
rescue StandardError => e
handler_exception = e
end

if error?(response)
error_response(response)
elsif response.is_a?(Rack::Response)
response
else
run_rescue_handler(method(:default_rescue_handler), Grape::Exceptions::InvalidResponse.new, endpoint)
run_rescue_handler(method(:default_rescue_handler), handler_exception || Grape::Exceptions::InvalidResponse.new, endpoint)
end
end

Expand Down
19 changes: 19 additions & 0 deletions spec/grape/api_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4693,4 +4693,23 @@ def uniqe_id_route

it { is_expected.to be_bad_request }
end

context "when rescue_from's block raises an error" do
subject { last_response.body }

let(:api) do
Class.new(described_class) do
rescue_from :all do
raise ArgumentError, 'This one!'
end
get { raise ArgumentError, 'Oops!' }
end
end

let(:app) { api }

before { get '/' }

it { is_expected.to eq('This one!') }
end
end