From 721dc1e15812468831f3eac21860e103547b5a9d Mon Sep 17 00:00:00 2001 From: Eric Date: Thu, 25 Jul 2024 11:40:10 +0200 Subject: [PATCH] Add a catch when running handler Add a spec --- lib/grape/middleware/error.rb | 5 ++++- spec/grape/api_spec.rb | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/lib/grape/middleware/error.rb b/lib/grape/middleware/error.rb index 6e5304607b..7705dab09d 100644 --- a/lib/grape/middleware/error.rb +++ b/lib/grape/middleware/error.rb @@ -116,8 +116,11 @@ 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) @@ -125,7 +128,7 @@ def run_rescue_handler(handler, error, endpoint) 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 diff --git a/spec/grape/api_spec.rb b/spec/grape/api_spec.rb index 14e2c92579..8faea2f6ee 100644 --- a/spec/grape/api_spec.rb +++ b/spec/grape/api_spec.rb @@ -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