2

I am using Ruby on Rails 3.2.2 and I would like to properly rescue the following process flow by raising a "custom" error message:

def rescue_method
  # sample_string.class
  # => String
  # sample_string.inspect
  # => "ARubyConstantThatDoesNotExist"

  begin
    build_constant(sample_string)
  rescue
    raise("My custom error message: #{build_constant(sample_string)} doesn't exist.")
  end
end

def build_constant(sample_string)
  "AModule::#{sample_string}".constantize
end

Note: I feel "forced" to use the constantize method also in the raised "custom" message in order to DRY code...

When the rescue_method is executed it seems that the raise("My custom error message") code is never executed and I get the following error:

uninitialized constant AModule::ARubyConstantThatDoesNotExist

How to properly display the raised "custom" message (since a further error exception is raised in the subsequent raised "custom" message)? What do you advice about?

4

3 回答 3

9

问题是您的build_constant方法正在做两件事:

  1. 构建类名。
  2. 使用 . 将名称转换为类constantize

当引发异常时,其中一件事想要使用另一件事。一个简单的解决方案是将这些单独的任务分开:

def build_class_name(sample_string)
  "AModule::#{sample_string}"
end

def rescue_method
  name = build_class_name(...)
  name.constantize
rescue NameError
  raise("My custom error message: #{name} doesn't exist.")
end

您还应该更具体地了解您正在寻找的异常,所以我免费添加了它。

于 2012-09-19T02:11:08.090 回答
7

如果您不想依赖捕获任何异常,可以使用safe_constantize( https://apidock.com/rails/ActiveSupport/Inflector/safe_constantize )。

目的相同,constantize但会nil在模块不存在时返回。

'UnknownModule::Foo::Bar'.safe_constantize  # => nil
于 2017-05-29T15:54:32.027 回答
0
begin
  "AModule::#{sample_string}".constantize
rescue SyntaxError, NameError => err
  raise("My custom error message")
end
于 2012-09-19T01:41:31.257 回答