How to continue when script fails(errors) and capture the output using Capistrano 3

2.5k views Asked by At

In Capistrano 2.x you could simply add :on_error => :continue like this:

task :bad_script, :on_error => :continue do
    my_error = capture('/path/to/tomcat/shutdown.sh')
end

I don't see any way to do this in Capistrano 3.x or ssh-kit (the underlying communication.) Any help would be appreciated.

task :bad_script do
  server_is_down
    on roles :all do
      begin
        server_is_down = capture('/path/to/tomcat/shutdown.sh')
      rescue
        #do something if server_is_down has the correct text
      end
    end
  end
end

I've tried surrounding the new way in begin/rescue blocks but that only stops it from erroring but it does not return the output from the error.

I'd still like to know how to do this but I figured out a way around needing it for my one case and that is to just set server is down if it fails.

task :bad_script do
  server_is_down = false
    on roles :all do
      begin
        execute('/path/to/tomcat/shutdown.sh')
      rescue
        server_is_down = true
      end
    end
  end
end

This is assuming that it only errors when the shutdown takes place.

2

There are 2 answers

3
Alex Siri On

The output from capture will only be returned if that method does not fail. If it raises an exception, there is no way it will return a value (as exception handling will take control). So, in order to get some response from the capture command, you'll need it to either return the value you need as part of the raised exception, or not to raise an exception, and just return an error code (plus the data you need to obtain).

0
user2342460 On

You can suppress the error and redirects stderr to a variable like this:

capture('output_from_tomcat_shutdown=`/path/to/tomcat/shutdown.sh 2>&1` || echo $output_from_tomcat_shutdown')