Skip to content

Commit

Permalink
Use default_error_status to specify the default status code returned …
Browse files Browse the repository at this point in the history
…from error\!.
  • Loading branch information
salimane authored and dblock committed Dec 4, 2013
1 parent 9b86c32 commit 35a6180
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ Next Release

* [#510](https://github.com/intridea/grape/pull/510): Support lambda-based default values for params - [@myitcv](https://github.com/myitcv).
* [#511](https://github.com/intridea/grape/pull/511): Add `required` option for OAuth2 middleware - [@bcm](https://github.com/bcm).
* [#520](https://github.com/intridea/grape/pull/520): Use `default_error_status` to specify the default status code returned from `error!` - [@salimane](https://github.com/salimane).
* Your contribution here.

#### Fixes
Expand Down
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -688,6 +688,19 @@ instead of a message.
error!({ "error" => "unexpected error", "detail" => "missing widget" }, 500)
```

### Default Error HTTP Status Code

By default Grape returns a 403 status code from `error!`. You can change this with `default_error_status`.

``` ruby
class API < Grape::API
default_error_status 400
get '/example' do
error! "This should have http status code 400"
end
end
```

### Handling 404

For Grape to handle all the 404s for your API, it can be useful to use a catch-all.
Expand Down
5 changes: 3 additions & 2 deletions lib/grape/endpoint.rb
Original file line number Diff line number Diff line change
Expand Up @@ -202,8 +202,9 @@ def version
# end user with the specified message.
#
# @param message [String] The message to display.
# @param status [Integer] the HTTP Status Code. Defaults to 403.
def error!(message, status = 403)
# @param status [Integer] the HTTP Status Code. Defaults to default_error_status, 403 if not set.
def error!(message, status = nil)
status = settings[:default_error_status] unless status
throw :error, message: message, status: status
end

Expand Down
9 changes: 9 additions & 0 deletions spec/grape/api_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1479,6 +1479,15 @@ def self.call(object, env)
get '/exception'
last_response.status.should eql 403
end
it 'uses the default error status in error!' do
subject.rescue_from :all
subject.default_error_status 400
subject.get '/exception' do
error! "rain!"
end
get '/exception'
last_response.status.should eql 400
end
end

context 'routes' do
Expand Down

0 comments on commit 35a6180

Please sign in to comment.