Skip to content

Commit

Permalink
feature: ability to handle standard error's descendants for unprocess…
Browse files Browse the repository at this point in the history
  • Loading branch information
sergei-kucher committed Jul 21, 2016
1 parent 6617804 commit 39880d3
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
1 change: 1 addition & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ group :development, :test do
end

gem 'mime-types', '< 3.0' if RUBY_VERSION < '2'
gem 'rack', '< 2.0' if RUBY_VERSION < '2.2.2'
gem 'migration_comments', '= 0.3.2' if RUBY_VERSION < '2'

# Specify your gem's dependencies in apress-api.gemspec
Expand Down
2 changes: 2 additions & 0 deletions lib/apress/api/api_controller/rescue.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ def unprocessable(exception_or_errors)
@errors =
if exception_or_errors.respond_to?(:record)
exception_or_errors.record.errors
elsif exception_or_errors.is_a?(StandardError)
{message: exception_or_errors.message}
else
exception_or_errors
end
Expand Down
22 changes: 21 additions & 1 deletion spec/controllers/api_controller/rescue_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def index
allow(controller).to receive(:record).and_return(record)
end

context 'when rescued from exeption' do
context 'when rescued from record invalid' do
controller do
def index
raise ActiveRecord::RecordInvalid.new(record)
Expand All @@ -91,6 +91,26 @@ def index
end
end

context 'when rescued from standard error' do
controller do
class CustomError < StandardError
end

rescue_from CustomError, with: :unprocessable

def index
raise CustomError.new("custom error")
end
end

it "renders error" do
get :index

expect(response.status).to eq 422
expect(json['errors']).to eq [{"message" => "custom error"}]
end
end

context 'when called from action' do
controller do
def index
Expand Down

0 comments on commit 39880d3

Please sign in to comment.