Skip to content

Error Handling

Albert Álef edited this page Feb 3, 2026 · 1 revision

Error Handling

RubyShell raises RubyShell::CommandError when a command fails (non-zero exit code).

Basic Error Handling

sh do
  begin
    rm("-rf", "nonexistent_folder")
  rescue RubyShell::CommandError => e
    puts "Command failed!"
  end
end

CommandError Properties

The exception provides detailed information about the failure:

Property Description
e.command The command that was executed
e.status Exit code
e.stderr Standard error output
e.stdout Standard output (if any)
e.message Human-readable error message
sh do
  begin
    git("push", "origin", "main")
  rescue RubyShell::CommandError => e
    puts "Command: #{e.command}"
    puts "Exit code: #{e.status}"
    puts "Error: #{e.stderr}"
  end
end

Handling Specific Exit Codes

sh do
  begin
    grep("pattern", "file.txt")
  rescue RubyShell::CommandError => e
    case e.status
    when 1
      puts "No matches found"
    when 2
      puts "File not found or error"
    else
      raise
    end
  end
end

Continuing on Failure

Sometimes you want to check if a command fails without raising:

sh do
  begin
    result = git("diff", "--quiet")
    puts "No changes"
  rescue RubyShell::CommandError
    puts "There are uncommitted changes"
  end
end

Logging Errors

Combine with debugging for detailed failure analysis:

sh(debug: true) do
  begin
    some_command("arg")
  rescue RubyShell::CommandError => e
    # Debug output will show execution details
    puts "Failed: #{e.message}"
  end
end

Next: Overwritten Methods

Clone this wiki locally