Skip to content

Commit

Permalink
Add AllowNil config option to Lint/SuppressedException (rubocop#9546)
Browse files Browse the repository at this point in the history
  • Loading branch information
corroded committed Mar 1, 2021
1 parent 6d8664c commit 930c812
Show file tree
Hide file tree
Showing 4 changed files with 89 additions and 2 deletions.
@@ -0,0 +1 @@
* Add `AllowNil` option for `Lint/SuppressedException` to allow/disallow `rescue nil`. ([@corroded][])
3 changes: 2 additions & 1 deletion config/default.yml
Expand Up @@ -2055,8 +2055,9 @@ Lint/SuppressedException:
StyleGuide: '#dont-hide-exceptions'
Enabled: true
AllowComments: true
AllowNil: true
VersionAdded: '0.9'
VersionChanged: '0.81'
VersionChanged: <<next>>

Lint/SymbolConversion:
Description: 'Checks for unnecessary symbol conversions.'
Expand Down
45 changes: 44 additions & 1 deletion lib/rubocop/cop/lint/suppressed_exception.rb
Expand Up @@ -64,12 +64,51 @@ module Lint
# rescue
# # do nothing
# end
#
# @example AllowNil: true (default)
#
# # good
# def some_method
# do_something
# rescue
# nil
# end
#
# # good
# begin
# do_something
# rescue
# # do nothing
# end
#
# # good
# do_something rescue nil
#
# @example AllowNil: false
#
# # bad
# def some_method
# do_something
# rescue
# nil
# end
#
# # bad
# begin
# do_something
# rescue
# nil
# end
#
# # bad
# do_something rescue nil
class SuppressedException < Base
MSG = 'Do not suppress exceptions.'

def on_resbody(node)
return if node.body
return if node.body && !nil_body?(node)
return if cop_config['AllowComments'] && comment_between_rescue_and_end?(node)
return if cop_config['AllowNil'] && nil_body?(node)

add_offense(node)
end
Expand All @@ -83,6 +122,10 @@ def comment_between_rescue_and_end?(node)
end_line = ancestor.loc.end.line
processed_source[node.first_line...end_line].any? { |line| comment_line?(line) }
end

def nil_body?(node)
node.body&.nil_type?
end
end
end
end
Expand Down
42 changes: 42 additions & 0 deletions spec/rubocop/cop/lint/suppressed_exception_spec.rb
Expand Up @@ -47,6 +47,48 @@ def foo
end
RUBY
end

context 'with AllowNil set to true' do
let(:cop_config) { { 'AllowComments' => false, 'AllowNil' => true } }

it 'does not register an offense for rescue block with nil' do
expect_no_offenses(<<~RUBY)
begin
do_something
rescue
nil
end
RUBY
end

it 'does not register an offense for inline nil rescue' do
expect_no_offenses(<<~RUBY)
something rescue nil
RUBY
end
end

context 'with AllowNil set to false' do
let(:cop_config) { { 'AllowComments' => false, 'AllowNil' => false } }

it 'registers an offense for rescue block with nil' do
expect_offense(<<~RUBY)
begin
do_something
rescue
^^^^^^ Do not suppress exceptions.
nil
end
RUBY
end

it 'registers an offense for inline nil rescue' do
expect_offense(<<~RUBY)
something rescue nil
^^^^^^^^^^ Do not suppress exceptions.
RUBY
end
end
end

context 'when empty rescue for defs' do
Expand Down

0 comments on commit 930c812

Please sign in to comment.