首页 > 解决方案 > 如何在 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中捕获异常的方法

标签: rubycapistrano

解决方案


我在这里采取了不同的方法

包装方法

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 任务


推荐阅读