class RuboCop::Cop::Lint::SuppressedExceptionInNumberConversion
Checks for cases where exceptions unrelated to the numeric constructors ‘Integer()`, `Float()`, `BigDecimal()`, `Complex()`, and `Rational()` may be unintentionally swallowed.
@safety
The cop is unsafe for autocorrection because unexpected errors occurring in the argument passed to numeric constructor (e.g., `Integer()`) can lead to incompatible behavior. For example, changing it to `Integer(potential_exception_method_call, exception: false)` ensures that exceptions raised by `potential_exception_method_call` are not ignored. [source,ruby] ---- Integer(potential_exception_method_call) rescue nil ----
@example
# bad Integer(arg) rescue nil # bad begin Integer(arg) rescue nil end # bad begin Integer(arg) rescue end # good Integer(arg, exception: false)
Constants
- EXPECTED_EXCEPTION_CLASSES
- MSG
Public Instance Methods
Source
# File lib/rubocop/cop/lint/suppressed_exception_in_number_conversion.rb, line 82 def on_rescue(node) if (method, exception_classes = begin_numeric_constructor_rescue_nil(node.parent)) return unless expected_exception_classes_only?(exception_classes) node = node.parent else return unless (method = numeric_constructor_rescue_nil(node)) end arguments = method.arguments.map(&:source) << 'exception: false' prefer = "#{method.method_name}(#{arguments.join(', ')})" prefer = "#{method.receiver.source}#{method.loc.dot.source}#{prefer}" if method.receiver add_offense(node, message: format(MSG, prefer: prefer)) do |corrector| corrector.replace(node, prefer) end end
rubocop:disable Metrics/AbcSize
Private Instance Methods
Source
# File lib/rubocop/cop/lint/suppressed_exception_in_number_conversion.rb, line 103 def expected_exception_classes_only?(exception_classes) return true unless (arguments = exception_classes.first) (arguments.values.map(&:source) - EXPECTED_EXCEPTION_CLASSES).none? end
rubocop:enable Metrics/AbcSize