Skip to content

Commit

Permalink
[rubocop#7842] Fix a false positive for Lint/RaiseException
Browse files Browse the repository at this point in the history
Resolve part of rubocop#7842.

This PR fixes a false positive for `Lint/RaiseException`
when raising Exception with explicit namespace.

`Exception` belonging to a namespace is expected to
inherit `StandardError`.

This PR makes `Lint/RaiseException` aware of the following differences:

```ruby
Gem::Exception.new.is_a?(StandardError) # => true
Exception.new.is_a?(StandardError)      # => false
```

On the other hand, the following case have not been resolved by this PR.

```ruby
module Gem
  def self.foo
    raise Exception
  end
end

Gem.foo #=> Gem::Exception
```

The above case will be resolved separately from this PR.
  • Loading branch information
koic committed Apr 3, 2020
1 parent 34e501e commit eda5183
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 2 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Expand Up @@ -2,6 +2,10 @@

## master (unreleased)

### Bug fixes

* [#7842](https://github.com/rubocop-hq/rubocop/issues/7842): Fix a false positive for `Lint/RaiseException` when raising Exception with explicit namespace. ([@koic][])

## 0.81.0 (2020-04-01)

### New features
Expand Down
4 changes: 2 additions & 2 deletions lib/rubocop/cop/lint/raise_exception.rb
Expand Up @@ -16,12 +16,12 @@ class RaiseException < Cop
MSG = 'Use `StandardError` over `Exception`.'

def_node_matcher :exception?, <<~PATTERN
(send nil? ${:raise :fail} (const _ :Exception) ... )
(send nil? ${:raise :fail} (const {cbase nil?} :Exception) ... )
PATTERN

def_node_matcher :exception_new_with_message?, <<~PATTERN
(send nil? ${:raise :fail}
(send (const _ :Exception) :new ... ))
(send (const {cbase nil?} :Exception) :new ... ))
PATTERN

def on_send(node)
Expand Down
7 changes: 7 additions & 0 deletions spec/rubocop/cop/lint/raise_exception_spec.rb
Expand Up @@ -80,4 +80,11 @@
it 'does not register an offense for `fail` without arguments' do
expect_no_offenses('fail')
end

it 'does not register an offense when raising Exception with explicit ' \
'namespace' do
expect_no_offenses(<<~RUBY)
raise Foo::Exception
RUBY
end
end

0 comments on commit eda5183

Please sign in to comment.