Skip to content

Commit c707742

Browse files
committed
Rescue truly all exceptions
1 parent 18c9d4b commit c707742

File tree

4 files changed

+11
-5
lines changed

4 files changed

+11
-5
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010

1111
* Your contribution here.
1212
* [#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).
13+
* []: Rescue truly all exceptions - [@mtsmfm](https://github.com/mtsmfm).
1314

1415
### 1.0.2 (1/10/2018)
1516

README.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -2071,7 +2071,7 @@ literally accepts every request.
20712071

20722072
## Exception Handling
20732073

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

20762076
```ruby
20772077
class Twitter::API < Grape::API
@@ -2098,7 +2098,7 @@ class Twitter::API < Grape::API
20982098
end
20992099
```
21002100

2101-
In this case ```UserDefinedError``` must be inherited from ```StandardError```.
2101+
```UserDefinedError``` can be inherited from any exception class.
21022102

21032103
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.
21042104

lib/grape/middleware/error.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ def call!(env)
3636
error_response(catch(:error) do
3737
return @app.call(@env)
3838
end)
39-
rescue StandardError => e
39+
rescue Exception => e # rubocop:disable Lint/RescueException
4040
is_rescuable = rescuable?(e.class)
4141
if e.is_a?(Grape::Exceptions::Base) && (!is_rescuable || rescuable_by_grape?(e.class))
4242
handler = ->(arg) { error_response(arg) }

spec/grape/middleware/exception_spec.rb

+7-2
Original file line numberDiff line numberDiff line change
@@ -103,8 +103,13 @@ def app
103103
run ExceptionSpec::OtherExceptionApp
104104
end
105105
end
106-
it 'does not trap errors other than StandardError' do
107-
expect { get '/' }.to raise_error(NotImplementedError, 'snow!')
106+
it 'sets the message appropriately' do
107+
get '/'
108+
expect(last_response.body).to eq('snow!')
109+
end
110+
it 'defaults to a 500 status' do
111+
get '/'
112+
expect(last_response.status).to eq(500)
108113
end
109114
end
110115
end

0 commit comments

Comments
 (0)