From 35a6180a3de765ead902dab4e9bd66b62fcb6843 Mon Sep 17 00:00:00 2001 From: Salimane Adjao Moustapha Date: Wed, 4 Dec 2013 10:01:15 -0500 Subject: [PATCH] Use default_error_status to specify the default status code returned from error\!. --- CHANGELOG.md | 1 + README.md | 13 +++++++++++++ lib/grape/endpoint.rb | 5 +++-- spec/grape/api_spec.rb | 9 +++++++++ 4 files changed, 26 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 230794ad62..bc5d3a2907 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/README.md b/README.md index cbb2923f83..8c7ce8c6ba 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/lib/grape/endpoint.rb b/lib/grape/endpoint.rb index 884785f1c1..9d58770fb6 100644 --- a/lib/grape/endpoint.rb +++ b/lib/grape/endpoint.rb @@ -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 diff --git a/spec/grape/api_spec.rb b/spec/grape/api_spec.rb index c942a12b21..d45d996d32 100644 --- a/spec/grape/api_spec.rb +++ b/spec/grape/api_spec.rb @@ -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