class RuboCop::Cop::Lint::RescueType
end
baz
rescue NameError
bar
def foo
# good
end
baz
rescue
bar
begin
# good
end
baz
rescue 1, ‘a’, “#{b}”, 0.0, [], {}
bar
def foo
# bad
end
baz
rescue nil
bar
begin
# bad
@example
if an exception is raised.
Check for arguments to ‘rescue` that will result in a `TypeError`
def autocorrect(corrector, node)
def autocorrect(corrector, node) rescued, _, _body = *node range = Parser::Source::Range.new(node.source_range.source_buffer, node.loc.keyword.end_pos, rescued.source_range.end_pos) corrector.replace(range, correction(*rescued)) end
def correction(*exceptions)
def correction(*exceptions) correction = valid_exceptions(exceptions).map(&:source).join(', ') correction = " #{correction}" unless correction.empty? correction end
def invalid_exceptions(exceptions)
def invalid_exceptions(exceptions) exceptions.select { |exception| INVALID_TYPES.include?(exception.type) } end
def on_resbody(node)
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.loc.keyword.join(rescued.source_range), message: format(MSG, invalid_exceptions: invalid_exceptions.map(&:source).join(', ')) ) do |corrector| autocorrect(corrector, node) end end
def valid_exceptions(exceptions)
def valid_exceptions(exceptions) exceptions - invalid_exceptions(exceptions) end