Saturday, September 1, 2012

Capistrano, errors, ensure, and on_rollback sample

namespace :fun do
  desc "Sample showing rescue, ensure, and on_rollback inside a transaction"
  task :stuff, :roles => :app do
    transaction do
      on_rollback { logger.debug "my rollback" }
      begin
        logger.debug "main"
        # Either run or run_locally will work the same
        # run_locally "false"
        run "false"
      rescue => e
        logger.debug "rescue #{e.class}"
        raise e
      ensure
        logger.debug "ensure"
      end
    end
  end
end

Command output:

cap fun:stuff
  * executingD `fun:stuff'
 ** transaction: start
  * main
  * executingB "false"
    servers: ["condor.austin.ibm.com"]
    [condor.austin.ibm.com] executingA command
    command finished in 771ms
  * rescue Capistrano::CommandError
  * ensure
*** [fun:stuff] rolling back
  * my rollback
failed: "bash -l -c 'false'" on condor.austin.ibm.com

Notes
  1. on_rollback executes only if the error happens while a transaction is active.
  2. on_rollback must also be defined within the transaction.
  3. raise e to make sure task exits with an error or higher level process will assume it completed successfully.
  4. ensure works as you expect.

No comments:

Post a Comment