class RuboCop::Cop::Lint::RescueType

Check for arguments to `rescue` that will result in a `TypeError` if an exception is raised.

@example

# bad
begin
  bar
rescue nil
  baz
end

# bad
def foo
  bar
rescue 1, 'a', "#{b}", 0.0, [], {}
  baz
end

# good
begin
  bar
rescue
  baz
end

# good
def foo
  bar
rescue NameError
  baz
end

Constants

INVALID_TYPES
MSG

Public Instance Methods

autocorrect(node) click to toggle source
# File lib/rubocop/cop/lint/rescue_type.rb, line 62
def autocorrect(node)
  rescued, _, _body = *node
  range = Parser::Source::Range.new(node.loc.expression.source_buffer,
                                    node.loc.keyword.end_pos,
                                    rescued.loc.expression.end_pos)

  lambda do |corrector|
    corrector.replace(range, correction(*rescued))
  end
end
on_resbody(node) click to toggle source
# File lib/rubocop/cop/lint/rescue_type.rb, line 44
def on_resbody(node)
  rescued, _, _body = *node
  return if rescued.nil?

  exceptions = *rescued
  invalid_exceptions = invalid_exceptions(exceptions)
  return if invalid_exceptions.empty?

  add_offense(
    node,
    location: node.loc.keyword.join(rescued.loc.expression),
    message: format(
      MSG, invalid_exceptions: invalid_exceptions.map(&:source)
                                                 .join(', ')
    )
  )
end

Private Instance Methods

correction(*exceptions) click to toggle source
# File lib/rubocop/cop/lint/rescue_type.rb, line 75
def correction(*exceptions)
  correction = valid_exceptions(exceptions).map(&:source).join(', ')
  correction = " #{correction}" unless correction.empty?

  correction
end
invalid_exceptions(exceptions) click to toggle source
# File lib/rubocop/cop/lint/rescue_type.rb, line 86
def invalid_exceptions(exceptions)
  exceptions.select do |exception|
    INVALID_TYPES.include?(exception.type)
  end
end
valid_exceptions(exceptions) click to toggle source
# File lib/rubocop/cop/lint/rescue_type.rb, line 82
def valid_exceptions(exceptions)
  exceptions - invalid_exceptions(exceptions)
end