Domanda

I have a Capistrano task excecuting a bash script:

task :test_task, roles: :ghost do
  begin
    run "./script.sh"
  rescue Capistrano::CommandError => e
    logger.important 'There was an error running the script'
  end
end

The script.sh returns exit 0 for success and exit 1, 2, 3 etc... for each error.

When exit is not 0, I'm logging "There was an error running the script". But, inside rescue, I want to know the exit status to log messages for specific errors.

Something like this:

rescue Capistrano::CommandError => e
  logger.important 'Error message 1' if e.exit_status == 1
  logger.important 'Error message 2' if e.exit_status == 2
  ...
end

Or, maybe, show an specific error given by script.sh:

rescue Capistrano::CommandError => e
  logger.important e.error_message
  #e.error_message this will be 'Error message 1' if exit status equals 1
  #e.error_message this will be 'Error message 2' if exit status equals 2
end
È stato utile?

Soluzione

You can trick it by echoing the exit code in your shell call:

run("./script.sh; echo EXIT_CODE=$?") do |ssh_channel, stream_id, output|
  output, exit_code = output.split("EXIT_CODE=")
  logger.important 'Error message 1' if exit_code == 1
  logger.important 'Error message 2' if exit_code == 2
  puts output
end
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top