我正在使用 Ruby on Rails 3.2.2,我想通过引发“自定义”错误消息来正确挽救以下流程:
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
注意:我觉得“被迫”使用 constantize
方法也在引发的“自定义”消息中以DRY代码...
当执行 rescue_method
时,似乎 raise("My custom error message")
代码从未执行,我收到以下错误:
uninitialized constant AModule::ARubyConstantThatDoesNotExist
如何正确显示引发的“自定义”消息(因为在后续引发的“自定义”消息中引发了进一步的错误异常)?你有什么建议?
最佳答案
问题是您的 build_constant
方法做了两件事:
- 构建类名。
- 使用
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
您还应该更具体地说明您正在寻找的异常,所以我免费添加了它。
关于ruby-on-rails - 如何挽救 `constantize`方法引发的错误异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12487404/