Search code examples
rubycapistrano

How to catch execption for proc in Ruby


I am using cap-ext-parallelize gem for parallel execution of the cap task for Capistrano

The parallelize method creates sessions which are passes as proc to a wrapper I have written to catch any exceptions that occur inside the session

parallelize do |session|
  session.run {deploy.restart} 
  session.run {queue.restart}
  session.run {daemon.restart}
end

Below is the wrapper code

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

Below is wrapper invocation

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

I want to catch any exceptions that occur inside the individual session

The wrapper continues even when there is an exception inside a session

I have tried to print the values

the sessions get passed as an Array to the wrapper and the array elements are proc

so basically I will need a way to catch exception inside a proc block

I came across this question ruby-proc-call-catching-exceptions but it does not give a way to catch exceptions in proc


Solution

  • I took a different approach here

    Wrapper Method

    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
    

    end

    Wrapper invocation

    parallelize do |session|
      session.run { parallel_execution("deploy.restart") }
      session.run { parallel_execution("queue.restart") }
      session.run { parallel_execution("daemon.restart") }
    end
    

    I passed the Rake task as a string to the wrapper and using eval I invoked the rake task