Question

I've written the following fact. The external command sometimes throws an error, which I want to catch. I've found many examples of how to catch an error using begin...end block. Unfortunately none of these concern the setcode do...end block. In fact, I cannot find any reference about the setcode. Can anyone shed a little light on this?

Facter.add(:docexists) do
  setcode do
    cryptdevice = File.read("/home/adam/.cryptdevice")
    if `cryptsetup luksOpen --key-file /home/adam/klucz.bin #{cryptdevice} crypt-tmp`
      tmp = `cryptsetup luksClose crypt-tmp`
      true
    else
      false
    end
  end
end
Was it helpful?

Solution

If I understand you correctly, you expect error from

if `cryptsetup luksOpen --key-file /home/adam/klucz.bin #{cryptdevice} crypt-tmp`

line. Then the begin-rescue-end block should work:

Facter.add(:docexists) do
  setcode do
    begin
      cryptdevice = File.read("/home/adam/.cryptdevice")
      if `cryptsetup luksOpen --key-file /home/adam/klucz.bin #{cryptdevice} crypt-tmp`
        tmp = `cryptsetup luksClose crypt-tmp`
        true
      else
        false
      end
    rescue => e
      # handle error
    end
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top