ruby - 如何在 Ruby 中捕获 proc 的执行
问题描述
我正在使用cap-ext-parallelize gem并行执行 Capistrano 的 cap 任务
parallelize 方法创建会话,这些会话作为 proc 传递给我编写的包装器,以捕获会话内发生的任何异常
parallelize do |session|
session.run {deploy.restart}
session.run {queue.restart}
session.run {daemon.restart}
end
下面是包装代码
def parallel_execution(thread_session, function_name)
begin
thread_session
rescue StandardError => e
puts "[Error] #{function_name} failed with error #{e.message}"
raise e.class, "[Error] #{function_name} failed with error #{e.message}"
end
end
下面是包装器调用
parallelize do |session|
parallel_execution(session.run {deploy.restart}, "deploy.restart")
parallel_execution(session.run {queue.restart}, "queue.restart")
parallel_execution(session.run {daemon.restart}, "daemon.restart")
end
我想捕获单个会话中发生的任何异常
即使会话中存在异常,包装器也会继续
我试图打印值
会话作为数组传递给包装器,并且数组元素是 proc
所以基本上我需要一种在 proc 块中捕获异常的方法
我遇到了这个问题ruby-proc-call- catch-exceptions但它没有提供在proc中捕获异常的方法
解决方案
我在这里采取了不同的方法
包装方法
def parallel_execution(thread_session)
begin
eval thread_session
rescue StandardError => e
puts "[Error] #{function_name} failed with error #{e.message}"
raise "[Error] #{thread_session} failed with error #{e.message}"
end
结尾
包装器调用
parallelize do |session|
session.run { parallel_execution("deploy.restart") }
session.run { parallel_execution("queue.restart") }
session.run { parallel_execution("daemon.restart") }
end
我将 Rake 任务作为字符串传递给包装器,并使用 eval 我调用了 rake 任务
推荐阅读
- tensorflow - 如何在 keras-tuner 中为超参数训练选择优化器和学习率
- python - 如何使用带有多个子图的 matplotlib 吸引人地排列标题和轴标签等图形和文本?
- java - 值按单个字符显示
- c# - 如何让我的敌人名单射击c#
- c++ - 苹果事业部 CSES Qustion 解决方案
- python - Leetcode 不同结果编译(#231 2 的幂)
- google-apps-script - 从电子表格中获取后将粗体文本粘贴到文档中
- javascript - 在 MutationObserver 中获取父级的问题
- angular - 我是否需要取消订阅已使用 Observable.from() 转换为 Observable 的 Promise?
- ruby-on-rails - 为什么rails作业(ApplicationJob)使用splat运算符?