在Ruby中,您可以在作业结束时编写rescue
以捕获可能出现的任何错误。我有一个函数(下面:a_function_that_may_fail
),如果不满足某些条件,它会让它抛出错误。以下代码效果很好
post = {}
# Other Hash stuff
post['Caption'] = a_function_that_may_fail rescue nil
但是如果函数失败,我想发帖['Caption']甚至没有设置。
我知道我能做到:
begin
post['Caption'] = a_function_that_may_fail
rescue
end
但感觉有点过分 - 是否有更简单的解决方案?
答案 0 :(得分:21)
问题是优先的。最简单的解决方案:
(post['Caption'] = a_function_that_may_fail) rescue nil
尽管如此,改变这样的优先级有点深奥。如果你的a_function_that_may_fail
重写nil
,如果它失败,可能会更好。
您还可以使用临时变量并测试nilness:
caption = a_function_that_may_fail rescue nil
post['Caption'] = caption unless caption.nil?
如果post['Caption']
没有引发异常但返回a_function_that_may_fail
,则不会设置nil
。
答案 1 :(得分:3)
post.store('Caption', a_function_that_may_fail) rescue nil
答案 2 :(得分:2)
确保您的方法返回nil
或false
:
def this_may_fail
some_logic rescue nil
end
然后,您可以使用if修饰符检查方法的返回值,并仅在值不是nil
或false
时指定值:
post['Caption'] = this_may_fail if this_may_fail
或者,如果您不想为if条件和赋值调用该方法两次,则可以将this_may_fail
的返回值缓存在局部变量中。
the_value = this_may_fail
post['Caption'] = the_value if the_value
还注意到rescue
修饰符仅捕获StandardError
及其子类。