Skip to content

Commit

Permalink
Add a catch when running handler
Browse files Browse the repository at this point in the history
Add a spec
  • Loading branch information
ericproulx committed Jul 25, 2024
1 parent 2b8567a commit 721dc1e
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
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

0 comments on commit 721dc1e

Please sign in to comment.