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

2

6

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.

Renfrow answered 14/1, 2014 at 20:59 Comment(0)
S
1

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')
Saintjust answered 22/9, 2015 at 11:56 Comment(0)
W
0

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).

Wampumpeag answered 14/1, 2014 at 22:2 Comment(3)
From what I see in github.com/capistrano/sshkit/blob/…, it should not raise any exceptionsWampumpeag
From github.com/capistrano/sshkit/blob/… "Execute and raise an error if something goes wrong on hosts do |host| execute!(:echo, '"Example Message!" 1>&2; false') end This will raise SSHKit::Command:Failed with the #message "Example Message!"` which will cause the command to abort."Renfrow
I don't have control over the raised exception, so how would I return some value in that exception? I get how capture works, I want it to return something when it does fail. There are lots of reasons a script would not work, I'd like to look for a certain one and do something when it has that "error."Renfrow

© 2022 - 2024 — McMap. All rights reserved.