Class: Rubocop::Cop::RescueException

Inherits:
Cop
  • Object
show all
Defined in:
lib/rubocop/cop/rescue_exception.rb

Constant Summary collapse

ERROR_MESSAGE =
'Avoid rescuing the Exception class.'

Instance Attribute Summary

Attributes inherited from Cop

#correlations, #debug, #disabled_lines, #offences

Instance Method Summary collapse

Methods inherited from Cop

#add_offence, cop_name, #has_report?, inherited, #initialize, #name

Constructor Details

This class inherits a constructor from Rubocop::Cop::Cop

Instance Method Details

#inspect(file, source, tokens, sexp) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/rubocop/cop/rescue_exception.rb', line 8

def inspect(file, source, tokens, sexp)
  each(:rescue, sexp) do |s|
    # TODO Improve handling of rescue One, Two => e
    if valid_case?(s)
      target_class = s[1][0][1][1]

      lineno = s[1][0][1][2].lineno

      add_offence(:warning,
                  lineno,
                  ERROR_MESSAGE) if target_class == 'Exception'
    end
  end
end

#valid_case?(s) ⇒ Boolean

Returns:

  • (Boolean)


23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/rubocop/cop/rescue_exception.rb', line 23

def valid_case?(s)
  if s[1].nil?
    # rescue with no args
    false
  elsif s[1][0] == :mrhs_new_from_args
    # rescue One, Two => e
    false
  elsif s[1][0][0] == :const_path_ref
    # rescue Module::Class
    false
  elsif s[1][0] == :mrhs_add_star
    # rescue *ERRORS
    false
  else
    true
  end
end