Skip to content

Commit

Permalink
Merge pull request #9587 from dvandersluis/issue/9586
Browse files Browse the repository at this point in the history
[Fix #9586] Update `Naming/RescuedExceptionsVariableName` to not register on inner rescues when nested.
  • Loading branch information
dvandersluis committed Mar 10, 2021
2 parents 0bb3303 + 11321c1 commit c2154be
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
@@ -0,0 +1 @@
* [#9586](https://github.com/rubocop/rubocop/issues/9586): Update `Naming/RescuedExceptionsVariableName` to not register on inner rescues when nested. ([@dvandersluis][])
10 changes: 10 additions & 0 deletions lib/rubocop/cop/naming/rescued_exceptions_variable_name.rb
Expand Up @@ -9,6 +9,11 @@ module Naming
# The `PreferredName` config option takes a `String`. It represents
# the required name of the variable. Its default is `e`.
#
# NOTE: This cop does not consider nested rescues because it cannot
# guarantee that the variable from the outer rescue is not used within
# the inner rescue (in which case, changing the inner variable would
# shadow the outer variable).
#
# @example PreferredName: e (default)
# # bad
# begin
Expand Down Expand Up @@ -62,6 +67,11 @@ def on_resbody(node)
offending_name = variable_name(node)
return unless offending_name

# Handle nested rescues by only requiring the outer one to use the
# configured variable name, so that nested rescues don't use the same
# variable.
return if node.each_ancestor(:resbody).any?

preferred_name = preferred_name(offending_name)
return if preferred_name.to_sym == offending_name

Expand Down
53 changes: 53 additions & 0 deletions spec/rubocop/cop/naming/rescued_exceptions_variable_name_spec.rb
Expand Up @@ -391,6 +391,59 @@ def main
RUBY
end
end

context 'with multiple branches' do
it 'registers and corrects each offense' do
expect_offense(<<~RUBY)
begin
something
rescue MyException => exc
^^^ Use `e` instead of `exc`.
# do something
rescue OtherException => exc
^^^ Use `e` instead of `exc`.
# do something else
end
RUBY

expect_correction(<<~RUBY)
begin
something
rescue MyException => e
# do something
rescue OtherException => e
# do something else
end
RUBY
end
end

context 'with nested rescues' do
it 'handles it' do
expect_offense(<<~RUBY)
begin
rescue StandardError => e1
^^ Use `e` instead of `e1`.
begin
log(e1)
rescue StandardError => e2
log(e1, e2)
end
end
RUBY

expect_correction(<<~RUBY)
begin
rescue StandardError => e
begin
log(e)
rescue StandardError => e2
log(e, e2)
end
end
RUBY
end
end
end

context 'with the `PreferredName` setup' do
Expand Down

0 comments on commit c2154be

Please sign in to comment.