抽象异常检查
我有一系列使用相同异常处理的方法。
如何将异常检查抽象为单独的函数?
请参阅下面的示例,非常感谢您的帮助!
def a
code
begin
rescue 1...
rescue 2...
rescue 3...
rescue 4...
end
end
def b
code
begin
rescue 1...
rescue 2...
rescue 3...
rescue 4...
end
end
I have a range of methods that use the same exception handling.
How can I abstract out the exception checking into a separate function?
See example below, thanks a lot for your help folks!
def a
code
begin
rescue 1...
rescue 2...
rescue 3...
rescue 4...
end
end
def b
code
begin
rescue 1...
rescue 2...
rescue 3...
rescue 4...
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最简单的解决方案是将代码作为块传递给方法,并在 begin/rescue 表达式中屈服于它:
您可能希望想出比 run_code_and_handle_exceptions 更简洁的方法名称!
The simplest solution would be to pass your code to a method as a block and yield to it within a begin/rescue expression:
You may want to come up with a more succinct method name than run_code_and_handle_exceptions!
在控制器中,我使用了rescue_from功能。非常干燥:
In controllers I've used rescue_from -functionality. It's quite DRY: