在Ruby中,抑制rescue子句内部异常的好方法是什么?
问题在于,rescue中的代码可能引发异常。对于这个用例,我想抑制它 那么,如何将救援包装成救援以抑制异常呢?你自己说的 把救援工作包起来 异常起始 除了在在Ruby中,抑制rescue子句内部异常的好方法是什么?,ruby,exception,error-handling,rescue,Ruby,Exception,Error Handling,Rescue,问题在于,rescue中的代码可能引发异常。对于这个用例,我想抑制它 那么,如何将救援包装成救援以抑制异常呢?你自己说的 把救援工作包起来 异常起始 除了在begin-rescue-end块中包装代码块外,没有其他特殊方法: begin do_something rescue Logger.write ... ...error handling... end …除非您使用的是ActiveSupport: …但这不是一个简单的Ruby问题,我注意到您没有在问题中添加rails标记。
begin-rescue-end
块中包装代码块外,没有其他特殊方法:
begin
do_something
rescue
Logger.write ...
...error handling...
end
…除非您使用的是ActiveSupport:
…但这不是一个简单的Ruby问题,我注意到您没有在问题中添加rails标记。不过,您可以自己实现suppress
。或者,就拿着这个:
suppress(Exception) do
# all exceptions will be suppressed
end
在你的营救中使用它:
def suppress(*exception_classes)
yield
rescue *exception_classes
end
在普通的旧Ruby中,它必须是一路救援(事实上,suppress
只是一个嵌套救援),但让我声明,救援所有异常是一个坏主意,本质上,不明确你要救援的异常,换句话说,通过不向rescue
传递异常类参数,您隐式地拯救了StandardError
,这是大多数异常的超类()。这可能导致难以找到的bug
begin
do_something
rescue
Logger.write ...
suppress Exception do
...error handling...
end
end
…与以下内容相同:
begin
rescue
end
最好了解您要拯救的异常并明确说明:
begin
rescue StandardError
end
有了这一点,您可以使用级联策略来拯救您的异常:
begin
rescue SomeApiError => e
# do something when this specific exception occurs
end
在上述情况下,将只运行与引发的异常匹配的rescue子句。但是,后续救援不会拯救救援块中的代码,只有begin
块中的代码才可救援
如果希望代码块即使在发生异常时也始终运行,请使用确保关键字:
begin
# do the thing
rescue SomeApiError => e
# specific rescue
rescue SomeOtherError => e
# more broad error handling
rescue
# catch all rescue
end
你自己说的
把救援工作包起来
异常起始
除了在begin-rescue-end
块中包装代码块外,没有其他特殊方法:
begin
do_something
rescue
Logger.write ...
...error handling...
end
…除非您使用的是ActiveSupport:
…但这不是一个简单的Ruby问题,我注意到您没有在问题中添加rails标记。不过,您可以自己实现suppress
。或者,就拿着这个:
suppress(Exception) do
# all exceptions will be suppressed
end
在你的营救中使用它:
def suppress(*exception_classes)
yield
rescue *exception_classes
end
在普通的旧Ruby中,它必须是一路救援(事实上,suppress
只是一个嵌套救援),但让我声明,救援所有异常是一个坏主意,本质上,不明确你要救援的异常,换句话说,通过不向rescue
传递异常类参数,您隐式地拯救了StandardError
,这是大多数异常的超类()。这可能导致难以找到的bug
begin
do_something
rescue
Logger.write ...
suppress Exception do
...error handling...
end
end
…与以下内容相同:
begin
rescue
end
最好了解您要拯救的异常并明确说明:
begin
rescue StandardError
end
有了这一点,您可以使用级联策略来拯救您的异常:
begin
rescue SomeApiError => e
# do something when this specific exception occurs
end
在上述情况下,将只运行与引发的异常匹配的rescue子句。但是,后续救援不会拯救救援块中的代码,只有begin
块中的代码才可救援
如果希望代码块即使在发生异常时也始终运行,请使用确保关键字:
begin
# do the thing
rescue SomeApiError => e
# specific rescue
rescue SomeOtherError => e
# more broad error handling
rescue
# catch all rescue
end
您可以在rescue中使用另一个开始rescue
块。或者在营救区什么也不做。我不知道你有什么问题。如果代码在您的rescue
块上引发异常,我想告诉您:只需修复错误:)您可以在rescue中使用另一个begin rescue
块。或者在营救区什么也不做。我不知道你有什么问题。如果代码在rescue
块上引发异常,我想告诉您:只需修复错误:)rescue
与rescue exception
不同rescue
与rescue exception
不同。