Skip to content

Commit

Permalink
Allow specifying a handler for grape_exceptions (ruby-grape#2342)
Browse files Browse the repository at this point in the history
* Allow specifying a handler for grape_exceptions

This allows you to customize the format of the error response for grape exceptions:

For example, you could do something like this:

```rb
rescue_from :grape_exceptions do |e|
  error!({ errors: [{ code: 'Error', message: e.message.squish }] }, e.status)
end
```

which would render like this:

```
{
  "errors": [
    {
      "code": "Error",
      "message": "Problem: message body does not match declared format Resolution: when specifying application/json as content-type, you must pass valid application/json in the request's 'body'"
    }
  ]
}
```

* match format

* Fix issue caught by tests

* Update README & CHANGELOG

* Add spec to demonstrate usage

* Fix rubocop offenses

* Fix rubocop offences
  • Loading branch information
mscrivo authored Jul 3, 2023
1 parent db7000b commit 96ac079
Show file tree
Hide file tree
Showing 8 changed files with 89 additions and 14 deletions.
23 changes: 14 additions & 9 deletions .rubocop_todo.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# This configuration was generated by
# `rubocop --auto-gen-config --auto-gen-only-exclude --exclude-limit 5000`
# on 2023-05-27 20:47:15 UTC using RuboCop version 1.50.2.
# on 2023-07-01 15:43:53 UTC using RuboCop version 1.50.2.
# The point is for the user to remove these configuration records
# one by one as the offenses are removed from the code base.
# Note that changes in the inspected code, or installation of new
Expand Down Expand Up @@ -100,6 +100,12 @@ Lint/MissingSuper:
- 'lib/grape/router/pattern.rb'
- 'lib/grape/validations/validators/base.rb'

# Offense count: 1
# Configuration parameters: CountComments, Max, CountAsOne, AllowedMethods, AllowedPatterns.
Metrics/MethodLength:
Exclude:
- 'lib/grape/endpoint.rb'

# Offense count: 2
# Configuration parameters: EnforcedStyleForLeadingUnderscores.
# SupportedStylesForLeadingUnderscores: disallowed, required, optional
Expand Down Expand Up @@ -134,7 +140,7 @@ RSpec/AnyInstance:
- 'spec/grape/api_spec.rb'
- 'spec/grape/middleware/base_spec.rb'

# Offense count: 342
# Offense count: 343
# Configuration parameters: Prefixes, AllowedPatterns.
# Prefixes: when, with, without
RSpec/ContextWording:
Expand Down Expand Up @@ -324,7 +330,7 @@ RSpec/MessageChain:
Exclude:
- 'spec/grape/middleware/formatter_spec.rb'

# Offense count: 136
# Offense count: 147
# Configuration parameters: .
# SupportedStyles: have_received, receive
RSpec/MessageSpies:
Expand All @@ -335,7 +341,7 @@ RSpec/MissingExampleGroupArgument:
Exclude:
- 'spec/grape/middleware/exception_spec.rb'

# Offense count: 765
# Offense count: 772
# Configuration parameters: Max.
RSpec/MultipleExpectations:
Exclude:
Expand Down Expand Up @@ -413,7 +419,7 @@ RSpec/MultipleMemoizedHelpers:
- 'spec/grape/request_spec.rb'
- 'spec/grape/validations/attributes_doc_spec.rb'

# Offense count: 2137
# Offense count: 2150
# Configuration parameters: EnforcedStyle, IgnoreSharedExamples.
# SupportedStyles: always, named_only
RSpec/NamedSubject:
Expand Down Expand Up @@ -478,7 +484,7 @@ RSpec/NamedSubject:
- 'spec/grape/validations/validators/presence_spec.rb'
- 'spec/grape/validations_spec.rb'

# Offense count: 174
# Offense count: 173
# Configuration parameters: Max, AllowedGroups.
RSpec/NestedGroups:
Exclude:
Expand Down Expand Up @@ -527,11 +533,10 @@ RSpec/RepeatedDescription:
- 'spec/grape/validations/validators/allow_blank_spec.rb'
- 'spec/grape/validations/validators/values_spec.rb'

# Offense count: 10
# Offense count: 8
RSpec/RepeatedExample:
Exclude:
- 'spec/grape/api_spec.rb'
- 'spec/grape/dsl/request_response_spec.rb'
- 'spec/grape/middleware/versioner/accept_version_header_spec.rb'
- 'spec/grape/validations/validators/allow_blank_spec.rb'

Expand Down Expand Up @@ -559,7 +564,7 @@ RSpec/StubbedMock:
- 'spec/grape/middleware/formatter_spec.rb'
- 'spec/grape/parser_spec.rb'

# Offense count: 114
# Offense count: 122
RSpec/SubjectStub:
Exclude:
- 'spec/grape/api_spec.rb'
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
* [#2332](https://github.com/ruby-grape/grape/pull/2332): Use ActiveSupport configurable - [@ericproulx](https://github.com/ericproulx).
* [#2333](https://github.com/ruby-grape/grape/pull/2333): Use custom messages in parameter validation with arity 1 - [@thedevjoao](https://github.com/TheDevJoao).
* [#2341](https://github.com/ruby-grape/grape/pull/2341): Stop yielding skip value - [@ericproulx](https://github.com/ericproulx).
* [#2342](https://github.com/ruby-grape/grape/pull/2342): Allow specifying a handler for grape_exceptions - [@mscrivo](https://github.com/mscrivo).
* Your contribution here.

#### Fixes
Expand Down
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2626,6 +2626,14 @@ class Twitter::API < Grape::API
end
```

If you want to customize the shape of grape exceptions returned to the user, to match your `:all` handler for example, you can pass a block to `rescue_from :grape_exceptions`.

```ruby
rescue_from :grape_exceptions do |e|
error!(e, e.status)
end
```

You can also rescue specific exceptions.

```ruby
Expand Down
3 changes: 2 additions & 1 deletion lib/grape/dsl/request_response.rb
Original file line number Diff line number Diff line change
Expand Up @@ -112,10 +112,11 @@ def rescue_from(*args, &block)

if args.include?(:all)
namespace_inheritable(:rescue_all, true)
namespace_inheritable :all_rescue_handler, handler
namespace_inheritable(:all_rescue_handler, handler)
elsif args.include?(:grape_exceptions)
namespace_inheritable(:rescue_all, true)
namespace_inheritable(:rescue_grape_exceptions, true)
namespace_inheritable(:grape_exceptions_rescue_handler, handler)
else
handler_type =
case options[:rescue_subclasses]
Expand Down
3 changes: 2 additions & 1 deletion lib/grape/endpoint.rb
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,8 @@ def build_stack(helpers)
rescue_options: namespace_stackable_with_hash(:rescue_options) || {},
rescue_handlers: namespace_reverse_stackable_with_hash(:rescue_handlers) || {},
base_only_rescue_handlers: namespace_stackable_with_hash(:base_only_rescue_handlers) || {},
all_rescue_handler: namespace_inheritable(:all_rescue_handler)
all_rescue_handler: namespace_inheritable(:all_rescue_handler),
grape_exceptions_rescue_handler: namespace_inheritable(:grape_exceptions_rescue_handler)

stack.concat namespace_stackable(:middleware)

Expand Down
2 changes: 1 addition & 1 deletion lib/grape/middleware/error.rb
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ def rescue_handler_for_grape_exception(klass)
return :error_response if klass == Grape::Exceptions::InvalidVersionHeader
return unless options[:rescue_grape_exceptions] || !options[:rescue_all]

:error_response
options[:grape_exceptions_rescue_handler] || :error_response
end

def rescue_handler_for_any_class(klass)
Expand Down
23 changes: 21 additions & 2 deletions spec/grape/dsl/request_response_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -148,13 +148,32 @@ def self.imbue(key, value)
it 'sets rescue all to true' do
expect(subject).to receive(:namespace_inheritable).with(:rescue_all, true)
expect(subject).to receive(:namespace_inheritable).with(:rescue_grape_exceptions, true)
expect(subject).to receive(:namespace_inheritable).with(:grape_exceptions_rescue_handler, nil)
subject.rescue_from :grape_exceptions
end

it 'sets rescue_grape_exceptions to true' do
it 'sets given proc as rescue handler' do
rescue_handler_proc = proc {}
expect(subject).to receive(:namespace_inheritable).with(:rescue_all, true)
expect(subject).to receive(:namespace_inheritable).with(:rescue_grape_exceptions, true)
subject.rescue_from :grape_exceptions
expect(subject).to receive(:namespace_inheritable).with(:grape_exceptions_rescue_handler, rescue_handler_proc)
subject.rescue_from :grape_exceptions, rescue_handler_proc
end

it 'sets given block as rescue handler' do
rescue_handler_proc = proc {}
expect(subject).to receive(:namespace_inheritable).with(:rescue_all, true)
expect(subject).to receive(:namespace_inheritable).with(:rescue_grape_exceptions, true)
expect(subject).to receive(:namespace_inheritable).with(:grape_exceptions_rescue_handler, rescue_handler_proc)
subject.rescue_from :grape_exceptions, &rescue_handler_proc
end

it 'sets a rescue handler declared through :with option' do
with_block = -> { 'hello' }
expect(subject).to receive(:namespace_inheritable).with(:rescue_all, true)
expect(subject).to receive(:namespace_inheritable).with(:rescue_grape_exceptions, true)
expect(subject).to receive(:namespace_inheritable).with(:grape_exceptions_rescue_handler, an_instance_of(Proc))
subject.rescue_from :grape_exceptions, with: with_block
end
end

Expand Down
40 changes: 40 additions & 0 deletions spec/grape/exceptions/body_parse_errors_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,46 @@ def app
end
end

context 'api with rescue_from :grape_exceptions handler with block' do
subject { Class.new(Grape::API) }

before do
subject.rescue_from :grape_exceptions do |e|
rack_response "Custom Error Contents, Original Message: #{e.message}", 400
end

subject.params do
requires :beer
end

subject.post '/beer' do
'beer received'
end
end

def app
subject
end

context 'with content_type json' do
it 'returns body parsing error message' do
post '/beer', 'test', 'CONTENT_TYPE' => 'application/json'
expect(last_response.status).to eq 400
expect(last_response.body).to include 'message body does not match declared format'
expect(last_response.body).to include 'Custom Error Contents, Original Message'
end
end

context 'with content_type xml' do
it 'returns body parsing error message' do
post '/beer', 'test', 'CONTENT_TYPE' => 'application/xml'
expect(last_response.status).to eq 400
expect(last_response.body).to include 'message body does not match declared format'
expect(last_response.body).to include 'Custom Error Contents, Original Message'
end
end
end

context 'api without a rescue handler' do
subject { Class.new(Grape::API) }

Expand Down

0 comments on commit 96ac079

Please sign in to comment.