Sha256: 464997fa9b8667dfa5c3528da6980c10a5d076fdadbddfe147ff636d379b49c3

Contents?: true

Size: 1.02 KB

Versions: 6

Compression:

Stored size: 1.02 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Lint
      # This cop checks for *rescue* blocks targeting the Exception class.
      #
      # @example
      #
      #   # bad
      #
      #   begin
      #     do_something
      #   rescue Exception
      #     handle_exception
      #   end
      #
      # @example
      #
      #   # good
      #
      #   begin
      #     do_something
      #   rescue ArgumentError
      #     handle_exception
      #   end
      class RescueException < Cop
        MSG = 'Avoid rescuing the `Exception` class. ' \
              'Perhaps you meant to rescue `StandardError`?'.freeze

        def on_resbody(node)
          return unless node.children.first
          rescue_args = node.children.first.children
          return unless rescue_args.any? { |a| targets_exception?(a) }

          add_offense(node, :expression)
        end

        def targets_exception?(rescue_arg_node)
          rescue_arg_node.const_name == 'Exception'
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
rubocop-0.49.1 lib/rubocop/cop/lint/rescue_exception.rb
rubocop-0.49.0 lib/rubocop/cop/lint/rescue_exception.rb
rubocop-0.48.1 lib/rubocop/cop/lint/rescue_exception.rb
rubocop-0.48.0 lib/rubocop/cop/lint/rescue_exception.rb
rubocop-0.47.1 lib/rubocop/cop/lint/rescue_exception.rb
rubocop-0.47.0 lib/rubocop/cop/lint/rescue_exception.rb