Skip to content

Commit

Permalink
Rescue truly all exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
mtsmfm committed Mar 1, 2018
1 parent 18c9d4b commit c707742
Show file tree
Hide file tree
Showing 4 changed files with 11 additions and 5 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

* Your contribution here.
* [#1737](https://github.com/ruby-grape/grape/pull/1737): Fix translating error when passing symbols as params in custom validations - [@mlzhuyi](https://github.com/mlzhuyi).
* []: Rescue truly all exceptions - [@mtsmfm](https://github.com/mtsmfm).

### 1.0.2 (1/10/2018)

Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2071,7 +2071,7 @@ literally accepts every request.

## Exception Handling

Grape can be told to rescue all `StandardError` exceptions and return them in the API format.
Grape can be told to rescue all exceptions and return them in the API format.

```ruby
class Twitter::API < Grape::API
Expand All @@ -2098,7 +2098,7 @@ class Twitter::API < Grape::API
end
```

In this case ```UserDefinedError``` must be inherited from ```StandardError```.
```UserDefinedError``` can be inherited from any exception class.

Notice that you could combine these two approaches (rescuing custom errors takes precedence). For example, it's useful for handling all exceptions except Grape validation errors.

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 @@ -36,7 +36,7 @@ def call!(env)
error_response(catch(:error) do
return @app.call(@env)
end)
rescue StandardError => e
rescue Exception => e # rubocop:disable Lint/RescueException
is_rescuable = rescuable?(e.class)
if e.is_a?(Grape::Exceptions::Base) && (!is_rescuable || rescuable_by_grape?(e.class))
handler = ->(arg) { error_response(arg) }
Expand Down
9 changes: 7 additions & 2 deletions spec/grape/middleware/exception_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,13 @@ def app
run ExceptionSpec::OtherExceptionApp
end
end
it 'does not trap errors other than StandardError' do
expect { get '/' }.to raise_error(NotImplementedError, 'snow!')
it 'sets the message appropriately' do
get '/'
expect(last_response.body).to eq('snow!')
end
it 'defaults to a 500 status' do
get '/'
expect(last_response.status).to eq(500)
end
end
end
Expand Down

0 comments on commit c707742

Please sign in to comment.