Class: RuboCop::Cop::Lint::ConstantOverwrittenInRescue

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
RangeHelp
Defined in:
lib/rubocop/cop/lint/constant_overwritten_in_rescue.rb

Overview

Checks for overwriting an exception with an exception result by use rescue ⇒.

You intended to write as rescue StandardError. However, you have written rescue ⇒ StandardError. In that case, the result of rescue will overwrite StandardError.

Examples:


# bad
begin
  something
rescue => StandardError
end

# good
begin
  something
rescue StandardError
end

Constant Summary collapse

MSG =
'`%<constant>s` is overwritten by `rescue =>`.'

Constants inherited from Base

Base::RESTRICT_ON_SEND

Instance Attribute Summary

Attributes inherited from Base

#config, #processed_source

Class Method Summary collapse

Instance Method Summary collapse

Methods included from AutoCorrector

support_autocorrect?

Methods inherited from Base

#active_support_extensions_enabled?, #add_global_offense, #add_offense, badge, #begin_investigation, callbacks_needed, #callbacks_needed, #config_to_allow_offenses, #config_to_allow_offenses=, #cop_config, cop_name, #cop_name, department, documentation_url, exclude_from_registry, #excluded_file?, #external_dependency_checksum, inherited, #initialize, #inspect, joining_forces, lint?, match?, #message, #offenses, #on_investigation_end, #on_new_investigation, #on_other_file, #parse, #ready, #relevant_file?, support_autocorrect?, support_multiple_source?, #target_rails_version, #target_ruby_version

Methods included from ExcludeLimit

#exclude_limit

Methods included from AutocorrectLogic

#autocorrect?, #autocorrect_enabled?, #autocorrect_requested?, #autocorrect_with_disable_uncorrectable?, #correctable?, #disable_uncorrectable?, #safe_autocorrect?

Methods included from IgnoredNode

#ignore_node, #ignored_node?, #part_of_ignored_node?

Methods included from Util

silence_warnings

Constructor Details

This class inherits a constructor from RuboCop::Cop::Base

Class Method Details

.autocorrect_incompatible_withObject



37
38
39
# File 'lib/rubocop/cop/lint/constant_overwritten_in_rescue.rb', line 37

def self.autocorrect_incompatible_with
  [Naming::RescuedExceptionsVariableName, Style::RescueStandardError]
end

Instance Method Details

#on_resbody(node) ⇒ Object



41
42
43
44
45
46
47
# File 'lib/rubocop/cop/lint/constant_overwritten_in_rescue.rb', line 41

def on_resbody(node)
  return unless (constant = overwritten_constant(node))

  add_offense(node.loc.assoc, message: format(MSG, constant: constant)) do |corrector|
    corrector.remove(range_between(node.loc.keyword.end_pos, node.loc.assoc.end_pos))
  end
end

#overwritten_constant(node) ⇒ Object



33
34
35
# File 'lib/rubocop/cop/lint/constant_overwritten_in_rescue.rb', line 33

def_node_matcher :overwritten_constant, <<~PATTERN
  (resbody nil? (casgn nil? $_) nil?)
PATTERN