Reputation: 38012
I need to rescue from 'Errno::ENOENT' in a Ruby on Rails 3.0.4 application. I currently have controller with the following code:
begin
`lame #{parameters}`
rescue Errno::ENOENT
logger.info "command 'lame' not found: ensure LAME is installed"
end
However, the log code is never called, but the logs show:
script/rails: No such file or directory - lame ...
If I create a ruby script with same snippet, the exception is rescued.
Upvotes: 8
Views: 20384
Reputation: 11395
In Ruby 1.8, Errno::ENOENT
is not raised by shell execution / back-ticks - the error you're seeing is standard error, printed by the shell. If you want to detect this, I'd recommend looking for an exit code of 127:
`lame #{parameters} 2>&1`
if $?.exitstatus == 127
logger.info "command 'lame' not found: ensure LAME is installed"
end
However, this will raise Errno::ENOENT
in Ruby 1.9.
You might consider checking the output from which lame
instead:
lame_installed = system("which lame >/dev/null")
# or even better
lame_available = !(lame_path = `which lame`.strip).empty? && File.executable?(lame_path)
Further reading:
Upvotes: 5