From eda5183d809a04341935b510c5af78296656938d Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Fri, 3 Apr 2020 14:06:31 +0900 Subject: [PATCH] [#7842] Fix a false positive for `Lint/RaiseException` Resolve part of #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. --- CHANGELOG.md | 4 ++++ lib/rubocop/cop/lint/raise_exception.rb | 4 ++-- spec/rubocop/cop/lint/raise_exception_spec.rb | 7 +++++++ 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 426ba4fcda5..7f2f31117af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/lib/rubocop/cop/lint/raise_exception.rb b/lib/rubocop/cop/lint/raise_exception.rb index fed736c57e8..e49175198d4 100644 --- a/lib/rubocop/cop/lint/raise_exception.rb +++ b/lib/rubocop/cop/lint/raise_exception.rb @@ -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) diff --git a/spec/rubocop/cop/lint/raise_exception_spec.rb b/spec/rubocop/cop/lint/raise_exception_spec.rb index 4433e55b9d6..5e3e9a310b4 100644 --- a/spec/rubocop/cop/lint/raise_exception_spec.rb +++ b/spec/rubocop/cop/lint/raise_exception_spec.rb @@ -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