diff --git a/CHANGELOG.md b/CHANGELOG.md index c88b65f80..40f3361e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,7 @@ * [#2521](https://github.com/ruby-grape/grape/pull/2521): Fixed typo in README - [@datpmt](https://github.com/datpmt). * [#2525](https://github.com/ruby-grape/grape/pull/2525): Require logger before active_support - [@ericproulx](https://github.com/ericproulx). * [#2524](https://github.com/ruby-grape/grape/pull/2524): Fix validators bad encoding - [@ericproulx](https://github.com/ericproulx). +* [#2530](https://github.com/ruby-grape/grape/pull/2530): Fix endpoint's status when rescue_from without a block - [@ericproulx](https://github.com/ericproulx). * Your contribution here. ### 2.2.0 (2024-09-14) diff --git a/lib/grape/middleware/error.rb b/lib/grape/middleware/error.rb index f201ee8ef..2dd39bc16 100644 --- a/lib/grape/middleware/error.rb +++ b/lib/grape/middleware/error.rb @@ -65,6 +65,7 @@ def find_handler(klass) def error_response(error = {}) status = error[:status] || options[:default_status] + env[Grape::Env::API_ENDPOINT].status(status) # error! may not have been called message = error[:message] || options[:default_message] headers = { Rack::CONTENT_TYPE => content_type }.tap do |h| h.merge!(error[:headers]) if error[:headers].is_a?(Hash) @@ -130,6 +131,7 @@ def run_rescue_handler(handler, error, endpoint) end def error!(message, status = options[:default_status], headers = {}, backtrace = [], original_exception = nil) + env[Grape::Env::API_ENDPOINT].status(status) # not error! inside route rack_response( status, headers.reverse_merge(Rack::CONTENT_TYPE => content_type), format_message(message, backtrace, original_exception) diff --git a/spec/grape/endpoint_spec.rb b/spec/grape/endpoint_spec.rb index 0674731fe..bcdf5f62e 100644 --- a/spec/grape/endpoint_spec.rb +++ b/spec/grape/endpoint_spec.rb @@ -115,6 +115,58 @@ def app expect(memoized_status).to eq(201) expect(last_response.body).to eq('Hello') end + + context 'when rescue_from' do + subject { last_request.env[Grape::Env::API_ENDPOINT].status } + + before do + post '/' + end + + context 'when :all blockless' do + context 'when default_error_status is not set' do + let(:app) do + Class.new(Grape::API) do + rescue_from :all + + post { raise StandardError } + end + end + + it { is_expected.to eq(last_response.status) } + end + + context 'when default_error_status is set' do + let(:app) do + Class.new(Grape::API) do + default_error_status 418 + rescue_from :all + + post { raise StandardError } + end + end + + it { is_expected.to eq(last_response.status) } + end + end + + context 'when :with' do + let(:app) do + Class.new(Grape::API) do + helpers do + def handle_argument_error + error!("I'm a teapot!", 418) + end + end + rescue_from ArgumentError, with: :handle_argument_error + + post { raise ArgumentError } + end + end + + it { is_expected.to eq(last_response.status) } + end + end end describe '#header' do