class RuboCop::Cop::Lint::RaiseException
end
end
raise Foo::Exception
def self.foo
module Foo
# good
end
end
raise Exception # This is qualified to ‘Gem::Exception`.
def self.foo
module Gem
# good
end
end
raise Exception # This is qualified to `Foo::Exception`.
def self.foo
module Foo
# bad - `Foo` is not an allowed implicit namespace
@example AllowedImplicitNamespaces: [’Gem’] (default)
raise MyError.new, ‘Error message here’
raise StandardError, ‘Error message here’
# good
raise Exception.new(‘Error message here’)
raise Exception, ‘Error message here’
# bad
@example
raised, which is a change in behavior.
This cop is unsafe because it will change the exception class being
@safety
(eg. ‘raise Namespace::Exception`).
Alternatively, use a fully qualified name with `raise`/`fail`
within the namespace.
If not allowed, a false positive may be registered if `raise Exception` is called<br>``, which allows `Gem::Exception` to be raised without an explicit namespace.
an array with the names of the namespaces to allow. By default, this is set to
to configure the cop to allow it by setting `AllowedImplicitNamespaces` to
If you have defined your own namespaced `Exception` class, it is possible
`Exception.new`. Use `StandardError` or a specific exception class instead.
Checks for `raise` or `fail` statements which raise `Exception` or
def allow_implicit_namespaces
def allow_implicit_namespaces cop_config['AllowedImplicitNamespaces'] || [] end
def check(node)
def check(node) lambda do |exception_class, cbase| return if cbase.nil? && implicit_namespace?(node) add_offense(exception_class) do |corrector| prefer_exception = if exception_class.children.first&.cbase_type? '::StandardError' else 'StandardError' end corrector.replace(exception_class, prefer_exception) end end end
def implicit_namespace?(node)
def implicit_namespace?(node) return false unless (parent = node.parent) if parent.module_type? namespace = parent.identifier.source return allow_implicit_namespaces.include?(namespace) end implicit_namespace?(parent) end
def on_send(node)
def on_send(node) exception?(node, &check(node)) || exception_new_with_message?(node, &check(node)) end