Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added custom exceptions to Grape. Updated validation errors to use ValidationError. #221

Merged
merged 1 commit into from
Aug 10, 2012
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.markdown
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
Next Release
============

* [#201](https://github.com/intridea/grape/pull/201): Added custom exceptions to Grape. Updated validations to use ValidationError that can be rescued. - [@adamgotterer](https://github.com/adamgotterer).
* [#211](https://github.com/intridea/grape/pull/211): Updates to validation and coercion: Fix #211 and force order of operations for presence and coercion - [@adamgotterer](https://github.com/adamgotterer).
* [#210](https://github.com/intridea/grape/pull/210): Fix: `Endpoint#body_params` causing undefined method 'size' - [@adamgotterer](https://github.com/adamgotterer).
* [#201](https://github.com/intridea/grape/pull/201): Rewritten `params` DSL, including support for coercion and validations - [@schmurfy](https://github.com/schmurfy).
Expand Down
5 changes: 5 additions & 0 deletions lib/grape.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ module Grape
autoload :Cookies, 'grape/cookies'
autoload :Validations, 'grape/validations'

module Exceptions
autoload :Base, 'grape/exceptions/base'
end
autoload :ValidationError, 'grape/exceptions/validation_error'

module Middleware
autoload :Base, 'grape/middleware/base'
autoload :Prefixer, 'grape/middleware/prefixer'
Expand Down
17 changes: 17 additions & 0 deletions lib/grape/exceptions/base.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
module Grape
module Exceptions
class Base < StandardError
attr_reader :status, :message, :headers

def initialize(args = {})
@status = args[:status] || nil
@message = args[:message] || nil
@headers = args[:headers] || nil
end

def [](index)
self.send(index)
end
end
end
end
4 changes: 4 additions & 0 deletions lib/grape/exceptions/validation_error.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
require 'grape/exceptions/base'

class ValidationError < Grape::Exceptions::Base
end
14 changes: 11 additions & 3 deletions lib/grape/middleware/error.rb
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,19 @@ def call!(env)
return @app.call(@env)
})
rescue Exception => e
raise unless options[:rescue_all] || (options[:rescued_errors] || []).include?(e.class)
handler = options[:rescue_handlers][e.class] || options[:rescue_handlers][:all]
is_rescuable = rescuable?(e.class)
if e.is_a?(Grape::Exceptions::Base) && !is_rescuable
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why woudln't rescuable? return true for a Grape::Exception::Base instead?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this code could be much simpler then:

if rescuable?(e.class)
   handler = 
else
   raise 
   handler = ...
end

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am sure I messed up this condition here, but you get the idea :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rescuable? checks if you have any rescue handlers set for an exception. It would evaluate to true if you had explicitly setup a rescue handler for Base (which you don't want to do, since it falls back on the default handler). I'll think a little bit about how to make this clearer.

Will also find some time in the next few days to address some old comments from other pull requests and updating the documentation.

handler = lambda { error_response(e) }
else
raise unless is_rescuable
handler = options[:rescue_handlers][e.class] || options[:rescue_handlers][:all]
end
handler.nil? ? handle_error(e) : self.instance_exec(e, &handler)
end

end

def rescuable?(klass)
options[:rescue_all] || (options[:rescued_errors] || []).include?(klass)
end

def handle_error(e)
Expand Down
2 changes: 1 addition & 1 deletion lib/grape/validations/coerce.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def validate_param!(attr_name, params)
if valid_type?(new_value)
params[attr_name] = new_value
else
throw :error, :status => 400, :message => "invalid parameter: #{attr_name}"
raise ValidationError, :status => 400, :message => "invalid parameter: #{attr_name}"
end
end

Expand Down
4 changes: 1 addition & 3 deletions lib/grape/validations/presence.rb
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
module Grape
module Validations

class PresenceValidator < Validator
def validate_param!(attr_name, params)
unless params.has_key?(attr_name)
throw :error, :status => 400, :message => "missing parameter: #{attr_name}"
raise ValidationError, :status => 400, :message => "missing parameter: #{attr_name}"
end
end
end

end
end
2 changes: 1 addition & 1 deletion lib/grape/validations/regexp.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ module Validations
class RegexpValidator < SingleOptionValidator
def validate_param!(attr_name, params)
if params[attr_name] && !( params[attr_name].to_s =~ @option )
throw :error, :status => 400, :message => "invalid parameter: #{attr_name}"
raise ValidationError, :status => 400, :message => "invalid parameter: #{attr_name}"
end
end
end
Expand Down
21 changes: 21 additions & 0 deletions spec/grape/api_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -669,6 +669,27 @@ def three

lambda{ get '/unrescued' }.should raise_error
end

it 'should not re-raise exceptions of type Grape::Exception::Base' do
class CustomError < Grape::Exceptions::Base; end
subject.get('/custom_exception'){ raise CustomError }

lambda{ get '/custom_exception' }.should_not raise_error
end

it 'should rescue custom grape exceptions' do
class CustomError < Grape::Exceptions::Base; end
subject.rescue_from CustomError do |e|
rack_response('New Error', e.status)
end
subject.get '/custom_error' do
raise CustomError, :status => 400, :message => 'Custom Error'
end

get '/custom_error'
last_response.status.should == 400
last_response.body.should == 'New Error'
end
end

describe ".error_format" do
Expand Down
21 changes: 21 additions & 0 deletions spec/grape/middleware/exception_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,16 @@ def call(env)
end
end
end

# raises a custom error
class CustomError < Grape::Exceptions::Base; end
class CustomErrorApp
class << self
def call(env)
raise CustomError, :status => 400, :message => 'failed validation'
end
end
end

def app
@app
Expand Down Expand Up @@ -116,6 +126,17 @@ def app
get '/'
last_response.status.should == 401
end

it 'should respond to custom Grape exceptions appropriately' do
@app ||= Rack::Builder.app do
use Grape::Middleware::Error, :rescue_all => false
run CustomErrorApp
end

get '/'
last_response.status.should == 400
last_response.body.should == 'failed validation'
end

end
end