-
Notifications
You must be signed in to change notification settings - Fork 4
Error Handling
Albert Álef edited this page Feb 3, 2026
·
1 revision
RubyShell raises RubyShell::CommandError when a command fails (non-zero exit code).
sh do
begin
rm("-rf", "nonexistent_folder")
rescue RubyShell::CommandError => e
puts "Command failed!"
end
endThe 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
endsh 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
endSometimes 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
endCombine 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
endNext: Overwritten Methods